gpt4 book ai didi

java - 用户输入验证有问题

转载 作者:行者123 更新时间:2023-11-30 05:51:30 25 4
gpt4 key购买 nike

这是我正在处理的程序的一小部分。我正在尝试检查用户是否输入了正确的号码。

他们有五个选项可供选择,因此他们可以点击 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com