java - Java中使用try-catch处理输入异常
问题描述
我已经为此工作了几个小时,我只是无法理解如何在这两个 do while 循环中实现 try-catch 以捕获用户输入非整数。我知道有这方面的帖子,但我似乎无法得到它。我非常感谢任何建议。
public class Paint {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
double wallHeight;
double wallWidth;
double wallArea = 0.0;
double gallonsPaintNeeded = 0.0;
final double squareFeetPerGallons = 350.0;
// Implement a do-while loop to ensure input is valid
// Handle exceptions(could use try-catch block)
do {
System.out.println("Enter wall height (feet): ");
wallHeight = scnr.nextDouble();
} while (!(wallHeight > 0));
// Implement a do-while loop to ensure input is valid
// Handle exceptions(could use try-catch block)
do {
System.out.println("Enter wall width (feet): ");
wallWidth = scnr.nextDouble();
} while (!(wallWidth > 0));
// Calculate and output wall area
wallArea = wallHeight * wallWidth;
System.out.println("Wall area: " + wallArea + " square feet");
// Calculate and output the amount of paint (in gallons)
// needed to paint the wall
gallonsPaintNeeded = wallArea/squareFeetPerGallons;
System.out.println("Paint needed: " + gallonsPaintNeeded + " gallons");
}
}
解决方案
首先在类中将 wallHeight 和 wallWidth 初始化为一个临时值(我们将使用 0):
double wallHeight = 0;
double wallWidth = 0;
然后你想放入scnr.nextDouble();
块try
中以捕获解析错误:
do {
System.out.println("Enter wall height (feet): ");
try{
wallHeight = scnr.nextDouble();
}catch(InputMismatchException e){
scnr.next(); //You need to consume the invalid token to avoid an infinite loop
System.out.println("Input must be a double!");
}
} while (!(wallHeight > 0));
注意块scnr.next();
中的。catch
您需要执行此操作才能使用无效令牌。否则它将永远不会从缓冲区中删除,并且scnr.nextDouble();
会继续尝试读取它并立即抛出异常。
推荐阅读
- python - 多个实例的 Python Flask 会话
- reactjs - 我得到一个 Uncaught Invariant Violation: could not find react-redux 上下文值;即使我的应用程序包含在 Provider 中
- android - Flutter 发布 APK 不工作,但调试 APK 工作
- python - Python:使用正则表达式和 while 循环来拆分 PDF 中的段落
- node.js - 求指导制作视频网络应用
- c++ - 在同一台机器上的虚拟 Windows 环境中运行的 macOS 应用程序和 C++ 应用程序之间进行通信
- javascript - Javascript - 获取到返回“来自原点‘null’的 API 已被 CORS 策略阻止”
- ssl - 隔离 Azure Kubernetes 服务 (AKS) SSL 错误
- c# - ASP.NET Web 窗体中的异步方法
- html - 消除页脚和内容之间的差距