【发布时间】:2021-06-16 17:15:28
【问题描述】:
我正在构建一个小程序来检查用户输入是否为数字。程序运行,但是当我的 catch 块捕获异常时,它以某种方式退出了它所在的嵌套 do-while 循环。
这是我的程序:
package TESTCLASS;
import java.util.Scanner;
public class Apples {
static int readValidInt(Scanner in, String prompt, int min, int max){
int validUserInput;
int userInput = 0; //have to initialize this variable since I will be using it in a block, setting it to 0 for now
int checker =1;
while(!in.hasNextInt()) { //Makes sure that user inputs an Integer, not String, double, etc
System.out.println("Sorry, only numbers in integer form is allowed. Please enter your choice as an integer between 1 and 4");
in.next();
}
do {
do {
try {
userInput = in.nextInt();
checker = 0;
}
catch (Exception e) {
System.out.println("Exception detectedddd");
in.nextLine(); // This line is to *clear the buffer* for Scanner
}
}while (checker ==1 );
if ( userInput >= min && userInput <= max) {
System.out.println("you have chosen board " + userInput );
validUserInput = userInput;
}
else {
System.out.println(prompt);
validUserInput = 0;
}
}while (validUserInput==0);
return validUserInput;
}
// Main function
public static void main (String args[]) {
Scanner input = new Scanner(System.in);
System.out.println("Choose a board style");
readValidInt(input, "Bruh that's not valid", 1, 4);
}
}
这是我的输出(如您所见,当我输入“5”时,会打印出两件事 - “Exception detectedddd”和“Bruh that's not valid”,但后一句是 if else 语句的一部分,由于存在异常,因此不应达到:
选择棋盘样式
100
Bruh 那是无效的
五个
检测到异常ddd
Bruh 那是无效的
六个
检测到异常ddd
Bruh 那是无效的
10
Bruh 那是无效的
1
你选择了板 1
【问题讨论】:
标签: java validation if-statement try-catch do-while