Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Java Prob with TextArea in Connection with Sqroot Exception

  1. Sep 4, 2016 #1

    I am creating a netbeans application. I am trying to handle square root exception. If the argument to sqrt is positive it should display its result in the text area otherwise, it would display a message that square not possible. Its displaying the result. For instance if the argument is positive (i.e. 25) , it displays its result (i.e. 5) in the text area but if the argument is negative it displays "NaN" in the text area instead of "Square root of negative numbers not possible" . Following is my code:


    int val=Integer.parseInt(strVal);


    double res= Math.sqrt(val);

    taResult.setText(" " + res);

    }catch(ArithmeticException e){

    taResult.setText("Square root of negative numbers not possible");


    Some body please guide me about this.

  2. jcsd
  3. Sep 4, 2016 #2


    User Avatar
    Science Advisor

    What would Math.sqrt() have to do in order for your error message to get printed?
  4. Sep 4, 2016 #3


    User Avatar
    Science Advisor
    Gold Member
    2017 Award

    If you look at the Math.sqrt() javadoc, you will see that it takes a double. You are passing an int. Also, the method does not throw an exception. If the result is invalid, it returns the double value NaN. You will have to look for that value rather than trying to catch an error.
  5. Sep 4, 2016 #4
    Okay. Thanks. Thats why its not coming in the catch block.
    I must use a different technique.
  6. Sep 4, 2016 #5


    Staff: Mentor

    That's not quite right. The argument to sqrt() can be zero, in which case the returned value is also zero.

    Instead of a try... catch block, have your code test the input value first before it takes the square root.

    I would do something like this. Note my change for the type of val from integer to double.
    Code (Java):


    double val = Double.parseDouble(strVal);
    if (val < 0)
    // Display appropriate message for negative input value
       double res= Math.sqrt(val);
       // Display appropriate value for valid input value
Share this great discussion with others via Reddit, Google+, Twitter, or Facebook

Have something to add?
Draft saved Draft deleted