如何处理 NumberFormatException: null in Java 取消退出程序

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

我的代码中有这个。整个程序工作正常,除了当您从输入名称对话框中单击取消时,它会进入下一个对话框,要求输入轮次。最后退出。假设在第一个对话框退出。

错误代码:

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

点击取消继续执行此操作,当它应该立即退出时:

知道如何解决这个错误吗?谢谢!

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));
}

试试这个可能对你有帮助:--

boolean proceed = false;
    while(!proceed){
        try{
            String iName = JOptionPane.showInputDialog (null, "Enter name:", JOptionPane.PLAIN_MESSAGE);
            System.out.println(iName);
            if(null != iName){
                int iRounds = Integer.parseInt(JOptionPane.showInputDialog (null, "Enter number of rounds:", JOptionPane.PLAIN_MESSAGE));
                System.out.println(iRounds);
            }
            proceed = true;
        }catch(NumberFormatException nf){
            nf.printStackTrace();
        }
    }