我无法使用我的可重新加载方法“菜单”工作,看起来它与扫描仪有关。
我确定这是一个简单的解决方案,但我找不到它
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;
}
}
}
我收到此错误消息:
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;"
答案 0 :(得分:1)
删除in.close()
。您的Scanner
封装了全局System.in
,一旦close()
,您将无法使用nextInt()
。
您可以将Scanner
提取到字段(或参数),如
public static int menu(Scanner in) {
// Scanner in = new Scanner(System.in);
// ...
// in.close();
// ...
我认为你想要main()
中的循环
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;
}
}