Java程序抛出NumberFormatException:无法解析null字符串求助
问题分析与解决
异常原因
NumberFormatException: Cannot parse null string 是因为调用 JOptionPane.showInputDialog() 时,若用户点击「取消」按钮或关闭输入窗口,方法会返回 null。而你直接将这个返回值传给 Integer.parseInt()/Double.parseDouble(),这两个方法无法解析null,因此抛出异常。
解决方案
在解析数字前,先判断输入是否为null或空字符串,避免直接解析非法值。同时可以增加输入合法性校验,防止用户输入非数字内容。
修改后的代码示例:
package semester2; import javax.swing.*; public class test { public static void main(String[] args) { // 处理姓名输入 String name = JOptionPane.showInputDialog("Enter your name"); JOptionPane.showMessageDialog(null, "Hello " + (name == null ? "Guest" : name)); // 处理年龄输入 String ageInput = JOptionPane.showInputDialog("Enter your age"); if (ageInput != null && !ageInput.trim().isEmpty()) { try { int age = Integer.parseInt(ageInput); JOptionPane.showMessageDialog(null, "You are " + age + " years old"); } catch (NumberFormatException e) { JOptionPane.showMessageDialog(null, "请输入合法的年龄数字"); } } else { JOptionPane.showMessageDialog(null, "未输入年龄"); } // 处理身高输入 String heightInput = JOptionPane.showInputDialog("Enter your height"); if (heightInput != null && !heightInput.trim().isEmpty()) { try { double height = Double.parseDouble(heightInput); JOptionPane.showMessageDialog(null, "You are " + height + " cm tall"); } catch (NumberFormatException e) { JOptionPane.showMessageDialog(null, "请输入合法的身高数字"); } } else { JOptionPane.showMessageDialog(null, "未输入身高"); } } }
关键改进点
- 先将输入内容存入字符串变量,判断是否为
null或空字符串后再解析 - 用
try-catch捕获解析非数字时的异常,给用户友好提示 - 对
null输入做默认值处理(比如姓名显示Guest)
内容的提问来源于stack exchange,提问作者tailwind
相关产品推荐
相关产品推荐

