当我运行代码时,它将在“ scanner.close()”行中正常运行。 之后,当我运行“ SumTenNumbers()”方法时...它将一次运行while循环的第一行,并因“ NoSuchElementException”而崩溃... 当我删除调用该方法的代码行上方的代码时,它运行良好... 为什么会发生这种情况,我该如何解决?
这是代码:
public class Main
{
public static void main(String[] args)
{
// we use the class "scanner" for input data
Scanner scanner = new Scanner(System.in); //System.in allows you to type input data into the console which can be returned into the console
System.out.println("Enter your name: ");
String name = scanner.nextLine();
System.out.println("Your name is " + name);
System.out.println("Enter your year of birth: ");
boolean isInt = scanner.hasNextInt();
if (isInt)
{
int yearOfBirth = scanner.nextInt();
int age = 2019 - yearOfBirth;
if (age >= 0 && age <= 120)
{
System.out.println("You are " + age + " years old");
}
else
{
System.out.println("Invalid year of birth");
}
}
else
{
System.out.println("Unable to parse year of birth");
}
scanner.close(); // we must close scanner
SumTenNumbers();
}
public static void SumTenNumbers()
{
var reader = new Scanner(System.in);
int sum = 0;
int count = 1;
while (count < 11)
{
System.out.println("Enter number " + count + ": ");
boolean valid = reader.hasNextInt();
if (valid)
{
int userNum = reader.nextInt();
sum += userNum;
count++;
}
else
{
reader.next();
System.out.println("INVALID");
}
}
System.out.println(sum);
reader.close();
}
}
这是我运行代码时的样子...
Enter your name:
Siddharth
Your name is Siddharth
Enter your year of birth:
2001
You are 18 years old
Enter number 1:
Exception in thread "main" java.util.NoSuchElementException
at java.base/java.util.Scanner.throwFor(Scanner.java:937)
at java.base/java.util.Scanner.next(Scanner.java:1478)
at com.company.Main.SumTenNumbers(Main.java:64)
at com.company.Main.main(Main.java:39)
Process finished with exit code 1
答案 0 :(得分:0)
行reader.close()
关闭Scanner
,并同时关闭System.in
。
此后,您将无法再读取stdin
(System.in
)。
为了防止这种情况,您可以:
仅使用一个Scanner
对象,并在最后一次使用后将其关闭
上次使用System.in
后关闭(使用Scanner
或System.in.close())
关闭System.in
永远不要关闭System.in
(问题:其他进程无法使用资源,stdin
也可以是文件,网络连接或其他东西)