4 Replies Latest reply: Oct 5, 2009 8:40 PM by 843789 RSS

    Catch Negative Number

    843789
      Hi experts,

      Is anyone can teach me how to catch negative input in GUI. I use NumberFormatException but it only catches String. I'd like to know in either way (try-catch and throwing exception.



      private void btnEnterActionPerformed(java.awt.event.ActionEvent evt)
      {                                            
      String amount = txtAmount.getText();
      if(!amount.equals(null) && !amount.equals(""))
      {
      try
      {
      double balance = depositTransaction.deposit(Double.parseDouble(this.txtAmount.getText()));
      lblBalance.setText("Your account balance is: $" + balance);
      }
      catch(NumberFormatException e)
      {
      lblBalance.setText("Invalid deposit entry");
      }
      txtAmount.setText("");
      btnEnter.setEnabled(false);
      }
      }

      Thanks heaps.
        • 1. Re: Catch Negative Number
          843789
          Just use a plain old if statement
          if (num < 0) {
              // do something
          }
          • 2. Re: Catch Negative Number
            843789
            I try this:

            catch(NumberFormatException e)
            {
            lblBalance.setText("Invalid deposit entry");

            double exception = Double.parseDouble(this.txtAmount.getText());

            if(exception < 0){
            lblBalance.setText("Invalid deposit entry");
            }
            }

            but it doesn't return the error massage.

            I'm still curious to use proper exception type for negative number though
            • 3. Re: Catch Negative Number
              843789
              There is no exception for negative numbers, because negative numbers are not exceptional when parsing for numbers.

              Don't try to handle with with an exception, or in the catch block. Try to parse the string to get a number. If it fails with a parse exception, tell the user. If it doesn't fail, then after parsing, check to see if the number is negative. If it's negative, then tell the user. You'd do this in the try block not the catch block.
              • 4. Re: Catch Negative Number
                843789
                Thank you for your explanation. It makes more sense now.