My infinite while loop is causing Java to throw NoSuchElementException

153 Views Asked by At

The system exit happens when it gets to the end of the program but it should work just like the inner while loop. Any suggestions are welcome. Here is the error message that i get:

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)

Here is my code

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

There are 1 best solutions below

0
On

Okay, so i solved the problem. In some of the code that i did not include(because of how long it was), i closed my scanner sooner than what i intended (in my methods). Such an error would bring up a:

Exception in thread "main" java.util.NoSuchElementException –

Anyone who has this problem, check your scanners. Thank you to anyone who took an interest!