2012-02-24 65 views
0

我尝试读取一个int和之后的字符串,这样:它打印爪哇 - 读字符串和int:java.util.NoSuchElementException

Save? Press 1 for yes, or 0 for no

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(); 

然后我得到

java.util.NoSuchElementException

我该如何解决?

+0

@deporter点丢失了怎么办?为什么downvote? – Bohemian 2012-02-24 09:34:40

回答

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();