我尝试读取一个int,然后以这种方式读取一个字符串:
String wantA = "";
Scanner in = new Scanner(System.in);
System.out.println("Enter A");
wantA = in.nextLine();
in.close();
// some code
int want = 0;
Scanner in = new Scanner(System.in);
System.out.println("Save? Press 1 for yes, or 0 for no");
want = in.nextInt();
in.close();
打印后
Save? Press 1 for yes, or 0 for no
然后我得到
java.util.NoSuchElementException
我该如何解决?
答案 0 :(得分:3)
删除in.close();
- 它会终止输入流(永远不会重新打开)。
而是继续使用相同的Scanner
将您的代码更改为:
Scanner in = new Scanner(System.in);
System.out.println("Enter A");
String wantA = in.nextLine();
System.out.println("Save? Press 1 for yes, or 0 for no");
int want = in.nextInt();