[英]java.util.NoSuchElementException - Scanner reading user input
[英]JAVA - user input java.util.NoSuchElementException from scanner
當打開多個掃描儀而不關閉時,導致異常。 但一旦關閉語句被刪除,就可以正常工作。
reader.close();
為什么關閉語句會這樣工作?
import java.util.Scanner;
public class IO {
public static void choices() {
boolean valid = true;
do{
System.out.println("What would you like to do?\n"
+ " press '1' for event
creation.\n"
+ " press '2' to display all
events.\n"
+ " press '3' to exit prgram.");
switch(inputInt()) {
case 1: newEvent(); break;
case 2: break;
case 3: System.out.println("Goodbye"); valid = false; break;
default: System.out.println("Invalid entery try again."); break;
}
}while(valid);
}
public static int inputInt() {
Scanner reader = new Scanner(System.in);
int input = reader.nextInt();
reader.close();
return input;
}
public static String inputString() {
Scanner reader = new Scanner(System.in);
String input = reader.next();
reader.close();
return input;
}
public static void newEvent() {
System.out.println("What is the event name?");
String name = inputString();
Event e1 = new Event(name);
Event.eventCreation(e1);
}
}
使用案例1時拋出此錯誤
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
正如文檔中明確指出的那樣:
public void close()
關閉此掃描儀。
如果尚未關閉此掃描器,則如果其基礎可讀文件也實現了Closeable接口,則將調用該可讀文件的close方法。
您也將關閉System.in
。
在此處提出問題時,重要的一點是要仔細閱讀所有適用的文檔,在這種情況下,這意味着閱讀Javadoc。
如果輸入已用盡,它將在方法'nextInt'上引發java.util.NoSuchElementException。 當關閉掃描器時,如果源實現了Closeable接口,它將關閉其輸入源。因此,當您調用“ reader.close()”時,它也會在輸入流中關閉system.。
System.in是靜態屬性。因此,關閉后不可用。
public final class System {
/* register the natives via the static initializer.
*
* VM will invoke the initializeSystemClass method to complete
* the initialization for this class separated from clinit.
* Note that to use properties set by the VM, see the constraints
* described in the initializeSystemClass method.
*/
private static native void registerNatives();
static {
registerNatives();
}
/** Don't let anyone instantiate this class */
private System() {
}
/**
* The "standard" input stream. This stream is already
* open and ready to supply input data. Typically this stream
* corresponds to keyboard input or another input source specified by
* the host environment or user.
*/
public final static InputStream in = null;
...
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.