运行时它会正确捕获异常,但是当我选择一个案例时会导致无限循环。我已经尝试了几个小时寻找解决方案,没有任何帮助。
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;
}
}
以下是交换机调用的方法示例:
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.");
}
}
}
答案 0 :(得分:0)
所以这是因为如果Scanner.nextInt()
与int不匹配,它会抛出异常,但是如果你调用Scanner.next()
,你会看到你之前输入的相同字符串。因此,每次进入循环时,它都会尝试解析与Integer相同的字符串输入,并且每次都会抛出异常。
您可以通过以下代码注意到此行为:
Scanner scanner = new Scanner(System.in);
while (contin) {
try {
System.out.println("Which program would you like to run?" + " Input 0 to exit the program.");
whatYouWant = scanner.nextInt();
contin = false;
} catch (Exception e) {
System.out.println(scanner.next());
System.out.println("Try again.");
contin = true;
}
}
scanner.close();
您会注意到,在调用scanner.next()
时,它仍将扫描相同的字符串。
要获得快速解决方案,您应该尝试Integer.parseInt(scanner.next());
代替scanner.nextInt();
答案 1 :(得分:-1)
我正在defualt
中阅读default
而不是switch
。