运行下述Java代码时出现java.lang.NullPointerException异常求助
解决Java声速计算代码中的NullPointerException问题
嘿,我看到你这段计算声速的Java代码抛出了java.lang.NullPointerException,咱们来拆解问题、搞定它~
问题根源
当用户在弹出的输入对话框里点击「取消」按钮,或者直接关闭对话框时,JOptionPane.showInputDialog()会返回null。这时候你直接调用medium.equalsIgnoreCase("air"),相当于在一个null对象上执行方法,这就触发了空指针异常。另外,你代码里的else分支没写完,要是用户输入了非air/water/steel的内容,也会有逻辑漏洞。
修复方案
我们需要先判断输入是否为null,再处理无效输入的情况,具体修改如下:
import javax.swing.JOptionPane; public class SpeedOfSound { public static void main(String[] args) { String medium; double time = 0; double distance = 0; // 获取介质输入并检查是否为null medium = JOptionPane.showInputDialog("Please enter a medium\n" + "(air, water, steel)"); if (medium == null) { JOptionPane.showMessageDialog(null, "You canceled the input, program exits."); return; // 直接退出程序,避免后续报错 } // 获取距离输入,同样添加null检查 String distanceInput = JOptionPane.showInputDialog("Please enter the distance the soundwave has to travel"); if (distanceInput == null) { JOptionPane.showMessageDialog(null, "You canceled the input, program exits."); return; } // 处理非数字输入的情况,避免NumberFormatException try { distance = Double.parseDouble(distanceInput); } catch (NumberFormatException e) { JOptionPane.showMessageDialog(null, "Invalid distance input, please enter a number."); return; } // 判断介质并计算时间 if (medium.equalsIgnoreCase("air")) { time = distance / 1100; } else if (medium.equalsIgnoreCase("water")) { time = distance / 4900; } else if (medium.equalsIgnoreCase("steel")) { time = distance / 16400; // 补充steel的声速计算 } else { JOptionPane.showMessageDialog(null, "Invalid medium, please enter air, water or steel."); return; } // 输出计算结果 JOptionPane.showMessageDialog(null, String.format("The time taken is %.2f seconds", time)); } }
关键修改点
- 添加null检查:在使用输入内容前,先判断是否为
null,从根源避免空指针异常 - 处理非数字输入:用
try-catch捕获NumberFormatException,防止用户输入非数字的距离导致崩溃 - 完善分支逻辑:补充
steel的计算分支,以及无效介质的提示,避免逻辑遗漏
内容的提问来源于stack exchange,提问作者fusion_ow
相关产品推荐
相关产品推荐

