我的无限循环导致Java抛出NoSuchElementException

时间:2014-11-16 01:09:48

标签: java java.util.scanner nosuchelementexception

系统退出在程序结束时发生,但它应该像内部while循环一样工作。欢迎任何建议。 以下是我收到的错误消息:

Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:907)
at java.util.Scanner.next(Scanner.java:1530)
at java.util.Scanner.nextInt(Scanner.java:2160)
at java.util.Scanner.nextInt(Scanner.java:2119)
at beast.main(beast.java:75)

这是我的代码

while(loopkey==1){//Call Methods and enables user to pick another exercise
    UserManual();
    System.out.print("Input the topickey here: ");//prompts for topic
    int topickey=kbd.nextInt();//scans topickey(which is an int)

    if(topickey==1)DoAdditionEx(j);//does addition
    else if(topickey==2)DoSubtractionEx(j);//does subtraction
    else if(topickey==3)DoMultiplicationEx(j);//does multiplication
    else{
        int errorkey=1;
        while(errorkey==1){
            System.out.print("ERROR: COMMAND NOT RECONGISED\nPlease reselect your topic of interest: ");
            topickey=kbd.nextInt();
            if(topickey==1 || topickey==2 || topickey==3) errorkey=0;
        }
    }
    if(topickey==1)DoAdditionEx(j);//does addition
    else if(topickey==2)DoSubtractionEx(j);//does subtraction
    else if(topickey==3)DoMultiplicationEx(j);//does multiplication

    System.out.println("Would you like to continue practicing? Please enter '1' for yes or '0' for no.");
    System.out.print("Input your choice here: ");

    int multitopickey=kbd.nextInt();
    if(multitopickey!=1) loopkey=0;
}

1 个答案:

答案 0 :(得分:0)

好的,所以我解决了这个问题。在我没有包含的一些代码中(因为它有多长时间),我比我想要的更快地关闭扫描仪(在我的方法中)。这样的错误会带来一个:

线程“main”中的异常java.util.NoSuchElementException -

遇到此问题的任何人,请检查您的扫描仪。 感谢任何感兴趣的人!