首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >线程"main“java.util.scanner异常

线程"main“java.util.scanner异常
EN

Stack Overflow用户
提问于 2017-11-15 13:19:45
回答 1查看 30关注 0票数 0
代码语言:javascript
复制
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%。

代码语言:javascript
复制
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();
    }
}

}

EN

回答 1

Stack Overflow用户

发布于 2017-11-15 13:35:09

Scanner scan = new Scanner(System.in);从你的生命周期中剔除。对scan.close;执行同样的操作,在退出main函数之前将其放入正确位置。当你close你的Scanner时,它也会关闭它的源代码。这可能是你例外的原因。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/47299910

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档