Prob with TextArea in Connection with Sqroot Exception

  • Context: Java 
  • Thread starter Thread starter zak100
  • Start date Start date
  • Tags Tags
    Connection
Join the discussion
Ask a follow-up here, or get your own question answered by working scientists, mathematicians and engineers — people, not an autocomplete.
Real named experts · corrections over time · the nuance an AI answer skips
4 replies · 2K views
zak100
Messages
462
Reaction score
11
Hi,

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:

strVal=tfValue.getText();

int val=Integer.parseInt(strVal);

try{

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.Zulfi.
 
Physics news on Phys.org
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.
 
  • Like
Likes   Reactions: jedishrfu
Okay. Thanks. Thats why its not coming in the catch block.
I must use a different technique.
Zulfi.
 
zak100 said:
If the argument to sqrt is positive it should display its result in the text area
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.
Java:
strVal=tfValue.getText();

double val = Double.parseDouble(strVal);
if (val < 0)
// Display appropriate message for negative input value
else
{
   double res= Math.sqrt(val);
   // Display appropriate value for valid input value
}