package sandbox2;
import java.util.Scanner;
public class Sandbox2
{
public static void main(String[] args)
{
for (int i = 0; i < 5; i++)
{
String s = askForProperty("Enter value for " + i + ": ");
System.out.println(i + " is: " + s);
}
}
private static String askForProperty(String message)
{
Scanner keyboard = new Scanner(System.in);
System.out.print(message);
String s = keyboard.nextLine();
keyboard.close();
return s;
}
}
当我运行上面的代码时,它会完美地返回第一个响应。当它尝试请求第二个响应时,它返回:
java.util.NoSuchElementException: No line found
为什么会返回此错误?每次调用方法 askForProperty 时,Scanner 都是一个全新的实例!它与 System.in 作为输入流有关吗?