gpt4 book ai didi

java - java中无效输入后重新提示用户(try and catch)

转载 作者:行者123 更新时间:2023-12-01 12:02:29 26 4
gpt4 key购买 nike

现在,它在发生一个错误后无限循环。如何让它在捕获后返回到尝试? boolean 条件声明正确,没有编译错误或任何错误。类中的其余代码有点困惑,因为我正在等待有关重试的答案。

<小时/>
double base = 0;
double height = 0;
double area = 0;
boolean again = true;
while (again) {
try {
System.out.print("Enter the length of base of triangle in cm : ");
base = input.nextDouble();
again = false;
} catch (Exception ex) {
System.out.println("Invalid input");
input.next();
}

try {
System.out.print("Enter the length of height of triangle in cm : ");
height = input.nextDouble();
} catch (Exception ex) {
System.out.println("Invalid Input");
String next = input.next();
}
area = (base * height) / 2;

最佳答案

使用 hasNextDouble() 而不是使用 try/catch 异常,因为您没有显式捕获 InputMismatchException

   while (again) {

// if the next is a double, print the value
if (input.hasNextDouble()) {
base = input.nextDouble();
System.out.println("You entered base: " + base);
again = false;
} else {
// if a double is not found, print "Not valid"
System.out.println("Not valid :" + input.next());
again = true;
}


}
again = true;
while (again) {

// if the next is a double, print the value
if (input.hasNextDouble()) {
height = input.nextDouble();
System.out.println("You entered height: " + height);
again = false;
} else {
// if a double is not found, print "Not valid"
System.out.println("Not valid :" + input.next());
again = true;
}


}
area = (base * height) / 2;

关于java - java中无效输入后重新提示用户(try and catch),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27893775/

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