Search code examples
javajoptionpanenumberformatexception

Java NumberFormatException error for input null


When I run my code below:

import javax.swing.JOptionPane;

public class HelloWorld{
    public static void main(String[] args){

        String dataStr=JOptionPane.showInputDialog("enter");

        if (dataStr!= null){
            int data=Integer.parseInt(dataStr);
            JOptionPane.showMessageDialog(null,"Ok"+data);
        }
    }
}

The terminal shows the following errors when I input null:

Exception in thread "main" java.lang.NumberFormatException: For input string: ""
    at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
    at java.lang.Integer.parseInt(Integer.java:592)
    at java.lang.Integer.parseInt(Integer.java:615)
    at HelloWorld.main(HelloWorld.java:9)

I think after adding the condition dataStr!=null I should not have such error. Is there anything wrong in my code?


Solution

  • Your problem is that the String returned from: JOptionPane.showInputDialog("enter");

    Can be one of three things:

    • null (if the dialog is cancelled)
    • A valid int numeric String -- then your Integer.parseInt will work
    • Or any other non-numeric String.

    When you simply press enter without entering a String, the returned value is the empty String, "", and this falls into the 3rd category. The best way to solve your problem is to 1) either parse your String inside a try/catch block, thus catching all invalid inputs, or 2) force the user input only numeric data, such as by using a JSlider or JSpinner.

    For example:

    if (dataStr != null){
    
        try {
            int data=Integer.parseInt(dataStr);
            JOptionPane.showMessageDialog(null,"Ok"+data);
        } catch (NumberFormatException nfe) {
            // notify user that input was invalid
        }
    
    }