简体   繁体   中英

while loop/switch statement

I am getting a " java.util.NoSuchElementException" that seems to point to my Scanner object within the while loop. everything works and prints fine, but when it loops through it always has the same error there.

I've tried to clear the buffer. I've tried moving my scanner outside of the loop. I've tried moving my instantiation of the object as well as the variable itself.

while(loop) {
  printMenu();
  scanA1.next();
        switch (choice) {

Exception in thread "main" java.util.NoSuchElementException

It probably happens because there are no more tokens left when scanA1.next() is called. You can check if there are tokens left like this:

  while(loop) {
    printMenu();
    if (scanA1.hasNext()) { // Checks if there are more tokens to read
        scanA1.next();
            switch (choice) {
...

It was because I made several different scanners w/in the methods of my switch that I closed. Once I deleted the .close(); the loop worked perfect. Thanks for the help though!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM