如何处理NumberFormatException:在Java中为null以取消并退出程序
我的密码里有这个。整个程序运行正常,除非在“输入名称”对话框中单击“取消”,然后进入下一个对话框,请求输入轮数。最后退出。假设它在第一个对话框中退出 错误代码:如何处理NumberFormatException:在Java中为null以取消并退出程序,java,null,numberformatexception,Java,Null,Numberformatexception,我的密码里有这个。整个程序运行正常,除非在“输入名称”对话框中单击“取消”,然后进入下一个对话框,请求输入轮数。最后退出。假设它在第一个对话框中退出 错误代码: String iName = JOptionPane.showInputDialog (null, "Enter name:", JOptionPane.PLAIN_MESSAGE); int iRounds = Integer.parseInt(JOptionPane.showInputDialog (null, "
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));
}
在显示第二个输入对话框之前,检查iName是否为空。如果按下
cancel
,则iName
将被设置为null
。这对我起到了作用。谢谢
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();
}
}