gpt4 book ai didi

java - 如何确保用户不输入字母

转载 作者:行者123 更新时间:2023-12-02 07:05:28 25 4
gpt4 key购买 nike

在我的程序中,用户必须选择他们想做的事情,然后点击选项旁边的数字,然后点击回车。

现在我有了它,所以任何不是选择的数字都会出错,但现在我想确保如果用户输入一个字母,例如“fadhahafvfgfh”,它会报错

这是我的代码...

import java.util.Scanner;

public class AccountMain {


public static void selectAccount(){


System.out.println("Which account would you like to access?");
System.out.println();
System.out.println("1 = Business Account ");
System.out.println("2 = Savings Account");
System.out.println("3 = Checkings Account");
System.out.println("4 = Return to Main Menu");

menuAccount();


}

public static void menuAccount(){

BankMain main = new BankMain();
BankMainSub sub = new BankMainSub();
BankMainPart3 main5 = new BankMainPart3();

Scanner account = new Scanner(System.in);

int actNum = account.nextInt();

if (actNum == 1){

System.out.println("*Business Account*");
sub.businessAccount();
}

else if (actNum == 2){

System.out.println("*Savings Account*");
main.drawMainMenu();
}

else if (actNum == 3){

System.out.println("*Checkings Account*");
main5.checkingsAccount();
}

else if (actNum == 4){
BankMain.menu();

}

}
}

最佳答案

您可以使用 Scanner#hasNextInt()为此。

if(account.hasNextInt())
account.nextInt();

Returns true if the next token in this scanner's input can be interpreted as an int value in the specified radix using the nextInt() method. The scanner does not advance past any input.

如果用户没有输入有效的,那么你可以说再见,下次见,如下所示。

    int actNum = 0;
if(account.hasNextInt()) {
//Get the account number
actNum = account.nextInt();
}
else
{
return;//Terminate program
}

否则您可以显示错误消息并要求用户重试有效帐号。

    int actNum = 0;
while (!account.hasNextInt()) {
// Out put error
System.out.println("Invalid Account number. Please enter only digits.");
account.next();//Go to next
}
actNum = account.nextInt();

关于java - 如何确保用户不输入字母,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12614817/

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