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;"
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;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With