现在,它在发生一个错误后无限循环地循环。捕获后如何使它回到尝试状态?布尔条件已正确声明,没有编译错误或其他任何东西。该类中的其余代码有些混乱,因为我在等待有关重试的答案。
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;