What is the result?
10 - 7 =
3
Congratulations, you got it correct!
Exception in thread "main" What is the result?
9 + 8 =
java.util.NoSuchElementException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at proj3.Project4App.main(Project4App.java:28)当我运行我的代码时,我得到了我的扫描器要通过的第一个循环,但后来我遇到了一个错误。我不确定我做错了什么?我需要让循环进行,直到10个问题被正确回答,20个问题被整体回答,或者正确答案的平均值超过85%。
package proj3;
import java.util.Scanner;
import java.util.Random;
/**
* <p> Title: Project 4: The Project4App Class </p>
* <p> Description: Creates an math game for children </p>
* @author Justin Abeles
*/
public class Project4App {
/**
* <p> Name: main method </p>
*
* @param args values to be sent to the method
*/
public static void main(String args[]){
int addCorrect = 0;
int addWrong = 0;
int subCorrect = 0;
int subWrong = 0;
while(true){
Question quiz = new Question();
Scanner scan = new Scanner(System.in);
System.out.println("What is the result?\n" + quiz.toString());
int age = scan.nextInt();
int answer = quiz.determineAnswer();
char operator = quiz.getOperator();
if(age == answer && operator == '+')
System.out.println("Congratulations, you got it correct!");
if((age == answer) && (operator == '-'))
System.out.println("Congratulations, you got it correct!");
if((age != answer) && (operator == '+'))
System.out.println("The correct answer for " + quiz.toString() + " is " + quiz.determineAnswer());
if((age != answer) && (operator == '-'))
System.out.println("The correct answer for " + quiz.toString() + " is " + quiz.determineAnswer());
if(age == answer && operator == '+')
addCorrect = addCorrect + 1;
else if(age == answer && operator == '-')
subCorrect = subCorrect + 1;
else if(age != answer && operator == '+')
addWrong = addWrong + 1;
else
subWrong = subWrong + 1;
scan.close();
}
}}
发布于 2017-11-15 13:35:09
把Scanner scan = new Scanner(System.in);从你的生命周期中剔除。对scan.close;执行同样的操作,在退出main函数之前将其放入正确位置。当你close你的Scanner时,它也会关闭它的源代码。这可能是你例外的原因。
https://stackoverflow.com/questions/47299910
复制相似问题