这是我正在处理的程序的一小部分。我正在尝试检查用户是否输入了正确的号码。
他们有五个选项可供选择,因此他们可以点击 1、2、3、4 或 5。然后按回车键。
所以我想检查以确保用户没有在 < 1 或 > 5 中键入任何内容。我让那部分工作了......但我只想知道是否有更简单的方法来做到这一点从我在下面的代码中所做的。
下一部分是我还想确保用户不会输入字母。像“gfgfadggdagdsg”这样的选择。
这是我正在处理的部分的代码....
public void businessAccount()
{
int selection;
System.out.println("\nATM main menu:");
System.out.println("1 - View account balance");
System.out.println("2 - Withdraw funds");
System.out.println("3 - Add funds");
System.out.println("4 - Back to Account Menu");
System.out.println("5 - Terminate transaction");
System.out.print("Choice: ");
selection = input.nextInt();
if (selection > 5){
System.out.println("Invalid choice.");
businessAccount();
}
else if (selection < 1){
System.out.println("Invalid choice.");
businessAccount();
}
else {
switch(selection)
{
case 1:
viewAccountInfo3();
break;
case 2:
withdraw3();
break;
case 3:
addFunds3();
break;
case 4:
AccountMain.selectAccount();
break;
case 5:
System.out.println("Thank you for using this ATM!!! goodbye");
}
}
}
最佳答案
你可以去掉检查 < 1
和 > 5
通过添加 default
案件。
try{
selection = input.nextInt();
switch(selection){
case 1:
viewAccountInfo3();
break;
case 2:
withdraw3();
break;
case 3:
addFunds3();
break;
case 4:
AccountMain.selectAccount();
break;
case 5:
System.out.println("Thank you for using this ATM!!! goodbye");
break;
default:
System.out.println("Invalid choice.");
businessAccount();
}
}catch(InputMismatchException e){
//do whatever you wanted to do in case input is not an int
}
关于java - 用户输入验证有问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12614142/