2

I'm new to programming and currently I'm writing the menu for a bank.

The user gets to choose, whether he/she is an admin or a customer by pressing 1 or 2. I want to write the code so that, if the user types other symbols than ints the program will send an error message and let the user choose again.

So far I have only managed to get the program to handle other integers than 1 and 2, using a while loop.

I'm thinking I should probably use try and catch, but I can't get it to work. I marked where I have tried the try/catch stuff with //----------.

error message when user input X instead of a number:

run:

Press 1 to login as customer or 2 to login as admin x
Exception in thread "main" java.util.InputMismatchException
  at java.util.Scanner.throwFor(Scanner.java:864)
  at java.util.Scanner.next(Scanner.java:1485)
  at java.util.Scanner.nextInt(Scanner.java:2117)
  at java.util.Scanner.nextInt(Scanner.java:2076)
  at bank.Bank.main(Bank.java:32)
Java Result: 1
BUILD SUCCESSFUL (total time: 5 seconds)

public class Bank {
  /**
   * @param args the command line arguments
   */
  public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    int ChoiceOne;

    int CustpNr;
    int CustChoice;

    int AdminpNr;
    int AdminChoice;

    System.out.print("Press 1 to login as customer or 2 to login as admin ");
    ChoiceOne = input.nextInt();

    while (ChoiceOne != 1 && ChoiceOne != 2) {
      // ---------------

      try {
        ChoiceOne = input.nextInt();
      } catch (Exception e) {
        continue;
      }

      // ----------------

      System.out.print(" Wrong number. Press 1 to login as customer or 2 to login as admin ");
      ChoiceOne = input.nextInt();
    }// ends while

    // The code below generates a menu for the customer if the user chooses 1
    // and a meny for the admin if the user chooses 2.

    if (ChoiceOne == 1) {
      System.out.print("Welcome customer. Please login by using your birthdate (yymmdd) ");
      CustpNr = input.nextInt();

      boolean quit = false;
      do {
        System.out.println("1. deposit money");
        System.out.println("2. Withdraw money");
        System.out.println("3. Check balance");
        System.out.print("Your choice, 0 to quit: ");
        CustChoice = input.nextInt();

        switch (CustChoice) {
        case 1:
          // deposit money
          break;
        case 2:
          // withdraw money
          break;
        case 3:
          // Check balance and accounts
          break;
        case 0:
          quit = true;
          break;
        default:
          System.out.println("Wrong choice.");
          break;
        }

        System.out.println();
      } while (!quit);

      System.out.println("Bye!");
    } else if (ChoiceOne == 2) {
      System.out.print("Welcome Admin. Please login using your birthdate (yymmdd) ");
      AdminpNr = input.nextInt();

      boolean quit = false;
      do {
        System.out.println("1. Add customer");
        System.out.println("2. Add account");
        System.out.println("3. List customer and accounts");
        System.out.println("4. Remove customer");
        System.out.println("5. Remove account");
        System.out.print("Your choice, 0 to quit: ");
        AdminChoice = input.nextInt();

        switch (AdminChoice) {
        case 1:
          // add customer
          break;
        case 2:
          // add account
          break;
        case 3:
          // List customer and accounts
          break;
        case 4:
          // ta bort kund
          break;
        case 5:
          // ta bort konto
          break;
        case 0:
          quit = true;
          break;
        default:
          System.out.println("Wrong choice.");
          break;
        }

        System.out.println();
      } while (!quit);

      System.out.println("Bye!");
    }
  }
}
t0mppa
  • 3,983
  • 5
  • 37
  • 48
Henrik
  • 23
  • 4
  • 1
    Looks about right - what's the problem? – Mureinik Oct 12 '14 at 18:54
  • @Henrik I posted my answer lemme know if it helps you :) – Kick Buttowski Oct 12 '14 at 19:08
  • Sorry I didnt add the error messages when running the program when i first posted the question. If i run the program and input "x" or another character it crashes. – Henrik Oct 12 '14 at 19:13
  • @Henrik did u solve ur issue? – Kick Buttowski Oct 13 '14 at 00:11
  • @Kick Buttowski Sorry for my late answer. I tried using the blueprint for hours but I didnt understand what I was doing wrong and then my brain crashed :P.. Anyways. I tried it again now and added 'input.next();' after 'else' and now it works. Thanks alot =) – Henrik Oct 13 '14 at 16:19
  • @KickButtowski Also I have a follow up question if you are interested in answering it :P. I find that if i remove the Scanner input = new Scanner(System.in); from the while loop and add it at the top as I usually do the loop goes infinite. Why is this? Problem was solved adding `input.next();` after`else`. – Henrik Oct 13 '14 at 16:31
  • @Henrik are you talking about your code or my sample? – Kick Buttowski Oct 13 '14 at 16:54
  • Im talking about my code. Your sample works great :) – Henrik Oct 13 '14 at 16:59

3 Answers3

2

You must used hasNextInt() to check if the entered number is type integer or not. If you entered any other types you will get java.util.InputMismatchException

public boolean hasNextInt()

Returns true if the next token in this scanner's input can be interpreted as an int value in the default radix using the nextInt() method. The scanner does not advance past any input. Returns: true if and only if this scanner's next token is a valid int value Throws: IllegalStateException - if this scanner is closed

You can use following example as your blue print

for example:

      int i = 0;
      while (i == 0) {
        Scanner input = new Scanner(System.in);
        System.out.println("Enter just int");
        if (input.hasNextInt()) {
            System.out.println(input.nextInt());
            System.out.println("good day");
            i = 1;
        } else {
            System.out.println("please enter type int");
        }
    }

enter image description here

Kick Buttowski
  • 6,709
  • 13
  • 37
  • 58
1

The problem is that you use ChoiceOne=input.nextInt() in two places. Only the one that is inside the loop is covered by try...catch.

Remove the call before the loop, and use a loop with a break, as suggested in other answers. You can either check in advance before calling nextInt() or catch the java.util.InputMismatchException.

RealSkeptic
  • 33,993
  • 7
  • 53
  • 79
0

Scanner input.nextInt(); will force the user until he enters a int when used on System.in, and will return the said value.

You don't have to caught its exceptions, meaning that having only the following code will be enough for forcinf your value to be either 1 or 2:

ChoiceOne=input.nextInt();

while (ChoiceOne != 1 && ChoiceOne !=2 )
     ChoiceOne=input.nextInt();
Mekap
  • 2,065
  • 14
  • 26
  • Ah ok. Sorry, I didnt add the error messages when I first posted. I tried what you suggested but if the user inputs "X" the program crashes and I get the error messages that i now added to the question. – Henrik Oct 12 '14 at 19:11