Search code examples
javainputuser-input

How to make sure user doesn't enter letters


In my program the user has to choose what they want to do and then hit the number next to the choice and then hit enter.

Right now I have it so that any number that isn't a choice will give an error but now I want to make sure it says error if the user types in a letter for example "fadhahafvfgfh"

here is my code...

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();

        }

    }
}

Solution

  • You can use Scanner#hasNextInt() for this.

    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.

    If user does not enter valid then you can say bye bye see you next time like below.

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

    Else you can show error message and ask user to retry for valid account number.

        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();