Mat*_*thy 2 java user-input input
这是我正在制作的程序的一小部分.我正在尝试检查用户是否输入了正确的号码.
他们有五种选择可供选择,因此可以点击1,2,3,4或5.然后按Enter键.
所以我想检查以确保用户没有在<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");
}
}
}
Run Code Online (Sandbox Code Playgroud)
您可以摆脱检查< 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
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
962 次 |
| 最近记录: |