Matt McCarthy
Matt McCarthy

Reputation: 115

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

        }

    }
}

Upvotes: 2

Views: 15783

Answers (5)

Amar Magar
Amar Magar

Reputation: 881

i think the accepted answer is correct, but we should make use of java features like exception handling in our code

// so our code should look like this

public static void main(String[] args) {

    int choice=0;
    Scanner scanner = new Scanner(System.in);
    StringReverse objReverse = new StringReverse();

    System.out.println("Menu");
    System.out.println("1.Reverse String");
    System.out.println("2.Exit");

    do {
            System.out.println("Enter your choice");
            try {
                choice = scanner.nextInt();
                switch(choice) {

                     case 1 :
                            System.out.println("Enter the string to reverse");
                            String inputString = new String();
                            inputString = scanner.next();
                            String reversedString = objReverse.reverse(inputString );
                            System.out.println("Reversed String is " + reversedString);
                            break;

                     case 2 :
                            System.out.println("Exiting...");
                            return;

                     default :
                            System.out.println("Default choice");
                            break;
               }
            } catch(Exception e) {
                    System.out.println("Please enter valid integer input");
                    scanner.next();
            }
   } while(choice != 2);
}

Upvotes: 1

PermGenError
PermGenError

Reputation: 46418

You can use Scanner.hasNextInt() or Integer.parseInt().

Scanner account = new Scanner(System.in);
String actNum = account.next();
try {
    Integer.parseInt(actNum);
} catch(ParseException ex) {
    sysout("please enter only numeric values")
}

Upvotes: 0

Rohit Jain
Rohit Jain

Reputation: 213281

Scanner account = new Scanner(System.in);
int count = 0;
while (true and count < 3) {
    if (!account.hasNextInt()) {
        int actNum = account.nextInt();
        break;
    } else {
         System.out.println("Enter an integer");
         count++;
         account.next();
    }
}

Upvotes: 2

Amit Deshpande
Amit Deshpande

Reputation: 19185

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

Upvotes: 5

st0le
st0le

Reputation: 33545

The Scanner has a hasNextInt() function that returns true if the next token is a Integer. So before calling nextInt() validate if hasNextInt() is true. If it fails, show a message to the user asking him to enter an integer. Note, The Integer doesn't necessarily needs to fall in your required range, so make sure you also have a final else to inform the user the number he entered was invalid.

Tip: Use Switch Case.

Upvotes: 0

Related Questions