简体   繁体   中英

Keep getting java.util.NoSuchElementException error when trying to make a loop

For a project I have to make to hangman game. Everything works but I'm trying make a loop which lets the user play again if he/she chooses.


import java.util.Scanner;
//this is the main method where I'm trying to add the loop//
public class hangMan {
    public static void main(String[] args) {
        String repeat = "y";
        while (repeat == "y") {
            Scanner sc = new Scanner(System.in);
            String w = randomWord("cat", "kite", "touch", "yellow", "abdomen");
            if (w.equals("cat")) {
                threeword();
            }
            if (w.equals("kite")) {
                fourword();
            }
            if (w.equals("touch")) {
                fiveword();
            }
            if (w.equals("yellow")) {
                sixword();
            }
            if (w.equals("abdomen")) {
                sevenword();
            }
            System.out.println("Do you want to play again? (y/n): ");
            repeat = sc.next();
            sc.close();
        }
    }

I was expecting for the loop to keep repeating the game if the user entered "y" for repeat and for the game to stop if the user entered any other character. However, instead I keep getting a java.util.NoSuchElementException error. I would appreciate if anyone can help me create a loop and explain to me why what I did to mess up. Thank you

  • Declare your Scanner object outside of the while loop
  • Write sc.close outside the while block ie before the end of main curly braces
  • Don't use ==, use equals() function. Note the difference between == and equals() function for String.

The complete code is:

public static void main(String[] args) {
        String repeat = "y";
        Scanner sc = new Scanner(System.in); //Fix: Only one scanner object will do
        while (repeat.equals("y")) {
            String w = randomWord("cat", "kite", "touch", "yellow", "abdomen");
            if (w.equals("cat")) {
                threeword();
            }
            if (w.equals("kite")) {
                fourword();
            }
            if (w.equals("touch")) {
                fiveword();
            }
            if (w.equals("yellow")) {
                sixword();
            }
            if (w.equals("abdomen")) {
                sevenword();
            }

            System.out.println("Do you want to play again? (y/n): ");
            repeat = sc.next();

            /*Fix: Close the scanner object only when user doesn't want to continue */
            if(!repeat.equals("y")){
                sc.close();
            }
        }
    }

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