试图制作一个程序来测试用户的算术技能。 level1方法会生成两个不超过10的随机数,然后测试用户的答案。当在if语句中调用level1方法时,它可以完美运行,但是在线程“ main”中抛出NoSuchElementException,如何避免这种情况?
public static void main(String[] args) {
if (level1() == true) {
System.out.println("passed level 1");
} else { System.out.println("failed level 1");
}
if (level2() == true) {
System.out.println("passed level 2");
}else {
System.out.println("failed level 2");
}
}
public static boolean level1() {
boolean passFail;
Scanner in = new Scanner(System.in);
Random ran = new Random();
int indexNum;
int num1 = ran.nextInt(10);
indexNum = 10 - num1;
int num2 = ran.nextInt(indexNum);
int sum = num1 + num2;
System.out.println("Level 1:");
System.out.println("What is " + num1 + " + " + num2);
if(sum == Integer.parseInt(in.next())) {
System.out.println("Correct!");
passFail = true;
} else {
System.out.println("Incorrect");
passFail = false;
}
in.close();
return passFail;
}