【发布时间】:2016-04-17 14:41:58
【问题描述】:
运行时它会正确捕获异常,但是当我选择一个案例时,它会导致无限循环。我已经尝试了几个小时寻找解决方案,但没有任何帮助。
int whatYouWant = 1;
boolean contin = true;
while (whatYouWant != 0) {
while (contin) {
try {
Scanner scanner = new Scanner(System.in);
System.out.println("Which program would you like to run?" + " Input 0 to exit the program.");
whatYouWant = scanner.nextInt();
contin = false;
scanner.close();
} catch (Exception e) {
System.out.println("Try again.");
contin = true;
}
}
AllCode a = new AllCode();
switch (whatYouWant) {
case 1:
// method call that calls a method with another try catch block
break;
case 2:
// another method call
break;
case 3:
// another method call and so on and so forth
break;
case 0:
whatYouWant = 0;
break;
default:
System.out.println("Please try again.");
break;
}
}
下面是 switch 调用的方法示例:
void multiplytheNumbers() {// Using the parameter to
boolean run = true;
while (run) {
try {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the 1st number:");
int num1 = sc.nextInt(); /// getting user input from the user.
System.out.println("Enter the 2nd number:");
int num2 = sc.nextInt(); /// getting more user input
int product = num1 * num2; /// using the multiplication operator
int sum = num1 + num2; /// using then addition operator
int diff = num1 - num1; /// using the subtraction operator
int quotient = num1 / num1; /// using the quotient operator
System.out.println(sum);
System.out.println(diff);
System.out.println(product);
System.out.println(quotient);
num1 = num1++; // using the increment operator to increase num1
// by 1
num2 = num2--; // using the decrement operator to decrease num2
// by 1
run = false;
sc.close();
} catch (Exception e) {
System.out.println("Invalid Input. Try again.");
}
}
}
【问题讨论】:
-
你的哪一个循环是无限的?
-
不要使用 try-catch 作为控制流的主要部分。如果您想防止用户提供不正确的值,只需检查扫描仪是否
hasNextInt(如果它没有通知用户并使用next使用不正确的令牌)。更多信息:Validating input using java.util.Scanner(可能重复)。 -
我建议你使用你的调试器来单步调试代码,看看它为什么会进入一个无限循环。一旦你知道如何使用它,使用调试器应该可以在几分钟内解决这个问题。