Announcement

Collapse
No announcement yet.

Programming question

Collapse
X
 
  • Filter
  • Time
  • Show
Clear All
new posts

  • You could also do something like:

    Code:
    double paymentValue;
    
    try {
        paymentValue = Double.parseDouble(payment.getText());
    } catch (NumberFormatException e) {
       popUpAMessageBox("that wasn't a number!");
    }
    
    if (paymentValue < 0) {
        popUpAMessageBox("can't be less than zero!");
    }

    Comment


    • Ok, I think I did it. It seems really crude and I'm guessing there are better ways to do what I just did but here's the code, tell me what you think:

      JFrame frame = new JFrame("Error");
      NumberFormatException problem = new NumberFormatException("Invalid Payment amount.");
      //Checks for negative numbers and throws exception if found.
      try {
      if (paymentValue < 0)
      throw problem;
      }
      catch (NumberFormatException exception){
      JOptionPane.showMessageDialog(frame,"Invalid payment amount.");
      }



      EDIT: THERE'S A PROBLEM. Ok, everything works but it's still entering in the data to the array. All I need now is a way to prevent it from entering into the array, and I'm not sure why it's still being entered in in the first place.

      Comment


      • My guess is that the try-catch is in your insert routine and that the code for insert is just after the catch. Try insert a return; in the catch part - execution continues after the catch even when there is an exception.
        With or without religion, you would have good people doing good things and evil people doing evil things. But for good people to do evil things, that takes religion.

        Steven Weinberg

        Comment


        • Yep, it worked. Thanks.

          Comment


          • Code:
            JFrame frame = new JFrame("Error");
            NumberFormatException problem = new NumberFormatException("Invalid Payment amount.");
            //Checks for negative numbers and throws exception if found.
            try {
                if (paymentValue < 0)
                    throw problem;
            }
            catch (NumberFormatException exception){
                JOptionPane.showMessageDialog(frame,"Invalid payment amount.");
            }
            Um. This code is precisely the same as the following:

            Code:
            JFrame frame = new JFrame("Error");
            if (paymentValue < 0)
                JOptionPane.showMessageDialog(frame, "Invalid payment amount.");
            Your try/catch there are completely superfluous.

            You should only be using try/catch to wrap around code where you call some other method (e.g. Double.parseDouble) that could raise an exception.

            Comment


            • Ah, ok. I thought I had to use try catch at all times in order to properly throw an exception.

              Comment


              • Generally you should only throw an exception if you are writing a method to be called elsewhere, and that method might encounter an "exceptional" (haha, get it?) condition that it isn't competent to handle.

                e.g. Double.parseDouble() throws NumberFormatExceptions because it doesn't know what the proper behavior of the application should be in the event "string that was passed in isn't actually a number". If the method that called Double.parseDouble() knows what to do, then it should catch the exception and handle it; otherwise, it should do nothing (as in, not even have a try/catch block) and just let the NumberFormatException percolate up the chain. If none of the methods in the chain (the "callstack") handles the exception, then eventually the Java virtual machine just says "oh, oops, I guess I should terminate".

                Comment


                • Well, Kuci is only partially right. In your case it is overkill unless it's an exercise in using it. The try-catch at local level is if you want to handle it locally and typically if your "try" can have several exceptions you want to handle individually. If you throw an exception it can be caught at a higher level in your structure.

                  Oh, and Kuci forgot the return; in his if()
                  With or without religion, you would have good people doing good things and evil people doing evil things. But for good people to do evil things, that takes religion.

                  Steven Weinberg

                  Comment


                  • Again, forgive me if this is something you've covered already and/or was completely obvious to you, but an explanation of the idea of the "call stack" is in order:

                    Your quintessential Java program begins execution at a method 'public static void main(String[] args)' in some class. main then does some computations and probably calls some methods. For example:

                    Code:
                    public class Example {
                        
                        public static void main(String args) {
                            // the call stack is just: [main]
                            foo();        
                        }
                        
                        public static void foo() {
                            // right now the call stack is: [main, foo]
                            bar();
                            // the call stack is still: [main, foo]
                            bas();
                            // and still: [main, foo]
                        }
                        
                        public static void bar() {
                            // the call stack is: [main, foo, bar]
                            xyzzy();
                            bas();
                        }
                        
                        public static void bas() {
                            // if I was called from foo(): [main, foo, bas]
                            // if I was called from bar(): [main, foo, bar, bas]
                        }
                        
                        public static void xyzzy() {
                            // the call stack is: [main, foo, bar, zyxxy]
                        }
                        
                    }
                    Every time you call a method, that method is added to the end of an ordered list. Every time you exit from a method back up to the method that called it - either through a return statement or by throwing an exception - the last element of that list is popped off.

                    When an exception is thrown, the program enters the following loop:

                    1. If control is currently inside a try/catch block, and that try/catch block catches the type of exception thrown, immediately jump out of the try {} block and into the relevant catch() {} block.
                    2. Otherwise, immediately transfer control up to the location in our calling method, where we were called, then go to 1.
                    3. If there was no calling method (i.e. we are main()), terminate the Java virtual machine on an error condition.

                    Comment


                    • Originally posted by BlackCat View Post
                      Well, Kuci is only partially right. In your case it is overkill unless it's an exercise in using it. The try-catch at local level is if you want to handle it locally and typically if your "try" can have several exceptions you want to handle individually. If you throw an exception it can be caught at a higher level in your structure.
                      Let's play the game called "Kuci explains general coding practices in a clear and simple way that applies to 99% of cases facing an inexperienced programmer and BlackCat doesn't add poorly worded footnotes that will just muddle the issue", mkay?

                      Oh, and Kuci forgot the return; in his if()
                      What the **** are you talking about? NEITHER BLOCK OF CODE RETURNS FROM THE ENCLOSING METHOD.

                      DriXnaK, I strongly encourage you to NOT READ BlackCat's advice because it is incoherent nonsense.

                      Comment


                      • Again, forgive me if this is something you've covered already and/or was completely obvious to you, but an explanation of the idea of the "call stack" is in order:
                        Tell me anything and everything you want. You guys at this point have taken the place of my course mentor who has made it clear she is useless. Assume I know nothing because I've been at this about 7 days now.

                        As far as calling methods and stuff, I'm still a little sketchy on how everything interacts, but it's starting to become clearer to me. I understand what you're saying now about the try catch statement.

                        I've got one more task to do yet to finish this first Java course. I'll probably end up asking questions on here at some point when I get stuck. I really hate Java, and this is not a very good Java course on top of it. Thanks for all the help so far.

                        Comment


                        • Originally posted by Kuciwalker View Post
                          Let's play the game called "Kuci explains general coding practices in a clear and simple way that applies to 99% of cases facing an inexperienced programmer and BlackCat doesn't add poorly worded footnotes that will just muddle the issue", mkay?
                          Kuci, you are quite funny - your "help" can't be that good since it needed correction a couple of times, actually missing quite crucial points. I seriously hope that you don't act as some kind of teacher in programming because then your pupils are in serious trouble.

                          What the **** are you talking about? NEITHER BLOCK OF CODE RETURNS FROM THE ENCLOSING METHOD.

                          DriXnaK, I strongly encourage you to NOT READ BlackCat's advice because it is incoherent nonsense.
                          Christ, have you lost your reading ability ? The try-catch is inside the adding to array method and the same goes for your if(). Without the return false data will be added.

                          DriXnaK, may I recommend that you are very careful using advice from Kuci ? You may have noticed that they have a tendency to be flawed.
                          With or without religion, you would have good people doing good things and evil people doing evil things. But for good people to do evil things, that takes religion.

                          Steven Weinberg

                          Comment


                          • God damn it we're playing the "BlackCat desperately tries to hide his ignorance" game again

                            The two blocks of code I had in post #110 are equivalent. In any given program, you could replace an occurrence of one of those blocks with the other, and the program's behavior would be unchanged. And, surprise, that's precisely what I claimed in my post.

                            Comment


                            • Originally posted by Kuciwalker View Post
                              God damn it we're playing the "BlackCat desperately tries to hide his ignorance" game again

                              The two blocks of code I had in post #110 are equivalent. In any given program, you could replace an occurrence of one of those blocks with the other, and the program's behavior would be unchanged. And, surprise, that's precisely what I claimed in my post.
                              Not quite - what we are playing is "Kuciwalker hasn't got a clue".

                              DriXnaK's code is like :

                              add_a_value()

                              try {
                              test_if_less_zero()
                              }
                              catch {
                              ...
                              }
                              add_value_to_array
                              }

                              yes, your if can easily replace the try-catch, but without a return the illegal value will be added. Now, please bow down and admit you were wrong - I will try to be mild in my verdict

                              Note: that was why my post #108 solved DriXnaK's problem
                              With or without religion, you would have good people doing good things and evil people doing evil things. But for good people to do evil things, that takes religion.

                              Steven Weinberg

                              Comment


                              • Just skimming, but BlackCat is right -- after the exception is caught, the code resumes execution immediately after the catch.

                                He could either put all of his adding logic in the try block (in which case as soon as the exception is thrown, it moves to the catch block and skips the code that could alter data), or he could add a return statement at the bottom.

                                I prefer the former over the latter. I try to only ever have one return statement per function.
                                "The issue is there are still many people out there that use religion as a crutch for bigotry and hate. Like Ben."
                                Ben Kenobi: "That means I'm doing something right. "

                                Comment

                                Working...
                                X