如何确保用户不输入字母

Mat*_*thy 2 java user-input input

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

现在我有它,所以任何不是选择的数字都会给出错误,但现在我想确保如果用户键入一个字母,例如"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();

        }

    }
}
Run Code Online (Sandbox Code Playgroud)

Ami*_*nde 5

您可以使用Scanner#hasNextInt().

if(account.hasNextInt())
  account.nextInt();
Run Code Online (Sandbox Code Playgroud)

如果此扫描器输入中的下一个标记可以使用nextInt()方法解释为指定基数中的int值,则返回true.扫描仪不会超过任何输入.

如果用户没有输入有效,那么你可以说再见,下次见到你.

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

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

    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();
Run Code Online (Sandbox Code Playgroud)