Search code examples
javanullnumberformatexception

How to handle NumberFormatException: null in Java to cancel and exit the program


I have this in my code. The whole program works fine, except when you click cancel from enter name dialog, in which it proceeds to the next dialog box asking for an input of rounds. And finally exits. It's suppose to exit on the first dialog box.

enter image description here

Code with error:

    String iName = JOptionPane.showInputDialog (null, "Enter name:", JOptionPane.PLAIN_MESSAGE);
    int iRounds = Integer.parseInt(JOptionPane.showInputDialog (null, "Enter number of rounds:", JOptionPane.PLAIN_MESSAGE));

enter image description here

Clicking cancel proceeds to this, when it's supposed to exit right away:

enter image description here

Any idea how to fix this error? Thanks!


Solution

  • String iName = JOptionPane.showInputDialog (null, "Enter name:", JOptionPane.PLAIN_MESSAGE);
    
    if( ((iName != null) && (iName .length() > 0)) {
        int iRounds = Integer.parseInt(JOptionPane.showInputDialog (null, "Enter number of rounds:", JOptionPane.PLAIN_MESSAGE));
    }