gpt4 book ai didi

java - Java中使用try-catch处理输入异常

转载 作者:行者123 更新时间:2023-12-01 19:32:18 25 4
gpt4 key购买 nike

我已经为此工作了几个小时,但我无法理解如何在这两个 do while 循环中实现 try-catch 来捕获用户输入的非 int 值。我知道有这方面的帖子,但我似乎看不到。我非常感谢任何建议。

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 block 中以捕获解析错误:

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

注意catch block 中的scnr.next();。您需要执行此操作才能使用无效 token 。否则它永远不会从缓冲区中删除,并且 scnr.nextDouble(); 将继续尝试读取它并立即抛出异常。

关于java - Java中使用try-catch处理输入异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59242617/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com