为什么以下代码不拒绝字符串和双输入? 我怎样才能改变呢?
int option;
do {
System.out.printf("Welcome %s, select an option\n", theUser.getFirstName());
System.out.println("1: Show previous transactions");
System.out.println("2: Withdraw");
System.out.println("3: Deposit");
System.out.println("4: Transfer");
System.out.println("5: Exit");
System.out.print("\nEnter Option: ");
option = input.nextInt();
if (option != 1 && option != 2 && option != 3 && option != 4 && option != 5){
System.out.println("\nError. Please choose a valid number");
}
} while(option != 1 && option != 2 && option != 3 && option != 4 && option != 5);
答案 0 :(得分:3)
你可以创建一个方法来获取一个整数并检查它是否真的像这样
private int getOption() {
int option;
try {
option = scanner.nextInt();
}
catch (InputMismatchException e) {
System.out.println("This was not valid input... " + scanner.next());
return getOption();
}
return option;
}
您还可以使用
缩小if块if(option < 0 || option > 5)
答案 1 :(得分:0)
除了触发异常外,您还可以使用一些正则表达式来检查输入是否只有1到5:
Scanner scn = new Scanner(System.in);
String input;
do{
System.out.print("Enter option (1-5): ");
input = scn.nextLine();
if(!input.matches("[1-5]+"))
System.out.println("Invalid input, please enter only 1 - 5");
}while(!input.matches("[1-5]+"));
//int option = Integer.parseInt(input); //if you need option to be an integer
SAMPLE OUTPUT:
Enter option (1-5): 3.3
Invalid input, please enter only 1 - 5
Enter option (1-5): 6
Invalid input, please enter only 1 - 5
Enter option (1-5): abc def
Invalid input, please enter only 1 - 5
Enter option (1-5):
Invalid input, please enter only 1 - 5
Enter option (1-5): 77
Invalid input, please enter only 1 - 5
Enter option (1-5): 3
Process completed.
由于我只是严格匹配1到5之间的值,因此它会阻止任何其他输入,例如
<1
和>5
)。