I wrote the following code to take input from user and parse it to double for further calculations. The problem is this program is giving me java.lang.NumberFormatException at compile time and this error java.lang.Double.parseDouble(Unknown Source). I don’t know why is this error is generated. So my questions are:
- What is the cause of this error?
- Why am I getting exception at compile time. In C++ if something went wrong, I would get exception at run time. I am unable to understand this behavior of Java.
Here is the code:
Note:
Multiplicand and Multiplier are JTextField
public void TakeInput()
{
double a,b;
String input1="1",input2="1";
input1=Multiplicand.getText();
input2=Multiplier.getText();
a=Double.parseDouble(input1);// converting string input to double
b=Double.parseDouble(input2);
....
}
When I click run or play button in eclipse, I get this exception. So thats why I am unable to give any input to these text fields
Regards
Your initial values for
MultiplicandandMultipliermust be validdoublevalues forDouble.parseDoublenot to throw aNumberFormatException.Note that if you wish to set the values in each
JTextFieldto1you could do:Also,
NumberFormatExceptionis a runtime or unchecked exception. You could wrap your assignments in atry/catchblock so that you can handle this exception gracefully.