0

I want to add two strings in java by getting data from two input fields. Result is shown in the 3rd field. I am using this code, but netbeans shows an error:

float num1,num2,result;
num1=Float.parseFloat(jTextField1.getText());
num2=Float.parseFloat(jTextField2.getText());
result=num1+num2;
jTextField3.setText(String.valueOf(result));
6
  • This code is for Add button butt when I press button show lot of thread and in out put this message is show Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: For input string: "Ahsan" at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1241) Commented Feb 16, 2014 at 6:59
  • Yes post the error and don't use the Netbeans GUI builder (IMO) Commented Feb 16, 2014 at 6:59
  • 1
    "Ahsan" is not a number. NumberFormatException clearly states that. Commented Feb 16, 2014 at 7:15
  • Maybe you're confusing which text fields are which. From the name of your variables, it looks like you're using GUI Builder. You should give your variables more semantic values like nameField so you know which one is which. You can do that by just right clicking the component from the design view and change variable name from the popup menu. Commented Feb 16, 2014 at 7:17
  • Yes I know that butt I want to add 2 strings Commented Feb 16, 2014 at 7:18

2 Answers 2

2

Thrown to indicate that the application has attempted to convert a string to one of the numeric types, but that the string does not have the appropriate format.

You will get a NumberFormatException if the text you entered isn't a proper number.Surround the parseFloat() statements in try-catch block. "Ahsan" isn't a number and hence cannot be parsed.

Make this little modification to your code:

try{
   num1=Float.parseFloat(jTextField1.getText());
   num2=Float.parseFloat(jTextField2.getText());
   result=num1+num2;
   jTextField3.setText(String.valueOf(result));
}catch(NumberFormatException e){
   e.printStackTrace();
}
Sign up to request clarification or add additional context in comments.

3 Comments

But but, in farci, "Ashan" is translated to five, so why won't it work?! kidding. +1
@peeskillet because swag. xD
Yes you are right but I want to add 2 strings and get as one string
1

If you get NumberFormatException it can happen in one of these 2 lines:

num1=Float.parseFloat(jTextField1.getText());
num2=Float.parseFloat(jTextField2.getText());

More specifically it is thrown from Float.parseFloat(). You pass unparsable value to this method. Check what jTextField1.getText() or jTextField2.getText() return. I believe that these fields are empty or contain text that cannot be interpreted as legal float.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.