Use Scanner in Rechargeable Menu Mode

I can't get my menu "reload" way to work, and it looks like it has something to do with the scanner.

I'm sure this is a simple solution, but I just can't seem to find it

 public class menuControl
{

    public static void main(String[] args)
{
        switch (menu())
        {
        case 1: System.out.println(1); menu();break;
        case 2: System.out.println(2); menu();break;
        case 3: System.out.println(3); menu();break;
        case 4: System.out.println(4); menu();break;
        case 0: System.out.println(0); menu();break;
        }
}
    public static int menu()
    {
        Scanner in = new Scanner(System.in);
        System.out.println("Choice 1");
        System.out.println("Choice 2");
        System.out.println("Choice 3");
        System.out.println("Choice 4");
        System.out.print("Choose: ");
        int choice = in.nextInt();
        System.out.println();
        in.close(); 
        if (choice > 0 && choice < 5)
        {
            return choice;
        }
        else
        {
            System.out.println("Wrong choice!");
            return 0;
        }
    }
}

      

I am getting this error message:

Exception in thread "main" java.util.NoSuchElementException
    at java.util.Scanner.throwFor(Unknown Source)
    at java.util.Scanner.next(Unknown Source)
    at java.util.Scanner.nextInt(Unknown Source)
    at java.util.Scanner.nextInt(Unknown Source)
    at Cashmachine.menu(Cashmachine.java:47) //The line"int choice = in.nextInt();"
    at Cashmachine.main(Cashmachine.java:23) //The line "case 1: System.out.println(1); menu();break;"

      

+3


source to share


1 answer


Delete in.close()

. Yours Scanner

transfers global System.in

as soon as you close()

can't use nextInt()

.

You can extract Scanner

in field (or argument) like

public static int menu(Scanner in) {
    // Scanner in = new Scanner(System.in);
    // ...
    // in.close();
    // ...

      



And I think you need a loop in main()

for example

Scanner in = new Scanner(System.in);
for (;;) {
    switch (menu(in)) {
    case 1:
        System.out.println(1);
        break;
    case 2:
        System.out.println(2);
        break;
    case 3:
        System.out.println(3);
        break;
    case 4:
        System.out.println(4);
        break;
    case 0:
        System.out.println(0);
        break;
    }
}

      

+1


source







All Articles