1

I m new, please have patience with me :)

I m not figure out why this method it s not working properly. It is creating me the account but, when the account was successfully created, it s not running well on the same method mainMenu(). I used a recursive call of the same method.... In the debug seems that it s not something well with my scanner from the second call of the method.

I m a Student

   public void mainMenu() {
    System.out.println("Select your option: ");
    System.out.println("1. Open a new account");
    System.out.println("2. Display all accounts");
    System.out.println("If you want to logout press 9");
    Scanner sc = new Scanner(System.in);
    int option = 0;
    do {
        try {
            option = sc.nextInt();
            System.out.println();
            switch (option) {
                case 1:
                    accountUtil.openNewAccount(userConsoleUtil.getUser().getUserName());
                    mainMenu();
                    break;
                case 9:
                    userConsoleUtil.logout();
                    displayLoginMenu();
                    break;
                default:
                    System.out.println("Invalid option! Try again");
            }
        } catch (InputMismatchException e) {
            System.out.println("Invalid option! Try again");
        }
        sc.nextLine();
    } while (option != 9);
    sc.close();
}

if the object account was created, it should return to beginning of the method, allowing to create a new account or exit with logout

Iosif
  • 29
  • 1
  • I'll go ahead and assume you close your Scanner in the `openNewAccount` method or in `userConsoleUtil` as well, so please read the linked question. – Tom Mar 29 '19 at 17:54
  • it s true...on all the methods I close the scanner at the end of the method. But at the begging of this method I opened a new Scanner. On debug I see another number for that scanner. It s not a new one? – Iosif Mar 29 '19 at 18:06
  • Like I said, read the linked post, it answers your question. – Tom Mar 29 '19 at 18:18
  • works with Scanner on Main. One more question...if on a method I will open a new Scanner and will not close it at the end of the method ( I don t want to put the parameter scanner to that method, because with parameter will not work again), sc.close from Main class will close that scanner too? – Iosif Mar 29 '19 at 19:08

2 Answers2

0

It feels like you mistakenly wrote sc.nextLine() which takes an input from the user. After the the end of catch block the line sc.nextLine() might give you unexpected output

0

Given your current code and the comments, it looks like you're creating scanners in your other methods and closing them. Don't do that. When you close the scanner, you also close System.in, leading to a NoSuchElementException.

Read this

Benjamin Urquhart
  • 1,626
  • 12
  • 18