javastringintegernumberformatexceptionawt-eventqueue

Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: For input string: " " Problem


I'm new to Java(we're learning it in a class), and a simple project we're currently working on is a Calculator. "Clear" should wipeout everything, "ADD" should sum the two numbers in the first and second text fields and Result would be shown in the result field. That is the case until I input my two numbers and press "ADD" and it gives me that(title) error. DOES ANYONE KNOW WHAT TO DO

The thing is, we're are trying to convert the numbers from strings to Integers so when I click "ADD" the numbers don't just appear side by side(Which was the case before) but actually sum up. For that I was told to use this code:

String no1=jTextField1.getText();
int num1= parseInt(no1);
String no2=jTextField2.getText();
int num2= parseInt(no2);
int answer=num1+num2;
String result=String.valueOf(answer);
jTextField3.setText(result);

I don't know whether the problem started from here.


Solution

  • Notice in the error message the preceding space:

    ...For input string: " 1"
    

    Try trimming all input strings (assuming spaces can be entered - a different issue)

    String no1=jTextField1.getText().trim();
    

    Reviewing the docs on Integer.parseInt explains in detail:

    Parses the string argument as a signed decimal integer. The characters in the string must all be decimal digits, except that the first character may be an ASCII minus sign '-' ('\u002D') to indicate a negative value or an ASCII plus sign '+' ('\u002B') to indicate a positive value.

    I also notice in what I think is your CLEAR button processing, you set the text fields to " ". That is likely the origin of your problem since when entering numbers one may not notice the extra space. Instead, use "" or null to clear any entry. In any event, the trim() is useful.

    From the JTextComponent docs:

    If the text is null or empty, has the effect of simply deleting the old text.


    And suggest you always include all information as text rather than images - helps in searching and reproducing errors if someone is so inclined. (I wanted to copy the error message to emphasize the error message - but couldn't because it is an image.)


    You should consider what happens when the user is not perfectly behaved - such as entering non-decimal numbers. Your code would fail in the same manner if "abc" is entered, for example.

    One way is to simply catch the NumberFormatException and handle it for error processing.

    There are other ways - such as filtering the input to prevent any non-decimal digit from being entered.