Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

use scanner in method with reloadable menu

I can´t get my reloadable method "menu" to work and it looks like it has something to do with scanner.

I´m sure it´s an easy solution but I just can´t 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 get 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;"
like image 420
Robert Avatar asked Aug 22 '26 05:08

Robert


1 Answers

Remove the in.close(). Your Scanner in wraps the global System.in, once you close() it you will not be able to use nextInt().

You could extract the Scanner to a field (or an argument) like

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

And I think you wanted a loop in main() like

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;
    }
}
like image 153
Elliott Frisch Avatar answered Aug 24 '26 21:08

Elliott Frisch



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!