尝试进行循环时,不断出现java.util.NoSuchElementException错误

时间:2019-11-03 04:32:50

标签: java

对于一个项目,我必须进行Hangman游戏。一切正常,但我正在尝试制作一个循环,让用户可以根据自己的选择再次播放。


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();
        }
    }

我期望如果用户输入“ y”进行重复,则循环将继续重复游戏,如果用户输入任何其他字符,则游戏将停止。但是,相反,我一直收到java.util.NoSuchElementException错误。如果有人可以帮助我建立循环并向我解释为什么我搞砸了,我将不胜感激。谢谢

2 个答案:

答案 0 :(得分:0)

  • 在while循环之外声明您的Scanner对象
  • 在while块外(即主花括号结束之前)写sc.close
  • 不要使用==,请使用equals()函数。请注意,==和String的equals()函数之间的区别。

答案 1 :(得分:0)

完整的代码是:

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();
            }
        }
    }