我正在制作一个程序来读取while循环中每个用户的输入响应,以检查该年是否是闰年。当我运行它时,控制台告诉我:
线程“main”中的异常java.util.NoSuchElementException
这意味着什么?如何解决问题以使其运行?
import java.util.Scanner;
public class GregorianCalendar {
public static void main(String[] args) {
int year, count, num;
//How many different years to look at
System.out.println("How many different years would you like to examine?");
Scanner scan = new Scanner(System.in);
count = scan.nextInt();
scan.close();
//Number of iterations
num = 0;
while (count != num)
{
num++;
System.out.println("Enter year");
Scanner keyboard = new Scanner(System.in);
year = keyboard.nextInt();
keyboard.close();
if (year % 400 == 0 || year % 4 == 0 && year % 100 != 0 && year > 1582) {
System.out.println(year + " is a leap year!");
}
else if (year % 100 == 0 && year % 400 != 0 || year % 100 != 0 && year > 1582) {
System.out.println(year + " is not a leap year!");
}
else {
System.out.println("Error! " + year + " cannot be before the year 1582!");
}
}
}
}
答案 0 :(得分:-1)
您遇到的问题是您正在关闭扫描仪,因此您将获得异常。试试这个:
public static void main(String[] args) {
int year, count, num;
//How many different years to look at
System.out.println("How many different years would you like to examine?");
Scanner scan = new Scanner(System.in);
count = scan.nextInt();
//Number of iterations
num = 0;
while (count != num)
{
num++;
System.out.println("Enter year");
year = scan.nextInt();
if (year % 400 == 0 || year % 4 == 0 && year % 100 != 0 && year > 1582) {
System.out.println(year + " is a leap year!");
}
else if (year % 100 == 0 && year % 400 != 0 || year % 100 != 0 && year > 1582) {
System.out.println(year + " is not a leap year!");
}
else {
System.out.println("Error! " + year + " cannot be before the year 1582!");
}
}
scan.close();
}
我还建议在代码中只使用一台扫描仪。