虽然Loop赢了退出

时间:2015-02-11 02:12:37

标签: java while-loop runtime-error

我正在尝试用Java创建一个Hangman游戏,我使用3个字符串来处理游戏。 randWord是从指定的单词列表数组(WORD_LIST)中随机选择的单词,randWordExt是扩展格式的randWord(例如penguin - > p e n g u n n),guessWord是在玩家猜测时更新的String。

    static String[] WORD_LIST =
    {
        //list of words implemented here
    };
    static String randWord;
    static String randWordExt = "";
    static String guessWord = "";
    static int LIVES = 10;

这是我的主要方法,问题是,当单词完全解决时,while循环不会退出。因此,永远不会显示最终消息。它完美地循环,猜测作品,但是当单词被解决时,它不会退出循环或显示最终的消息。

    public static void main(String[] args) {

    boolean running = true;
    Scanner input = new Scanner(System.in);

        generateWord();
        System.out.println("You have " + LIVES + " lives to guess the word! \n" + guessWord);
        while(running){

            guessLetter(input.next().charAt(0));
            if(guessWord == randWordExt){

                running = false;

            } else {

                System.out.println(guessWord);
                System.out.println("Lives left: " + LIVES);

            }

        }
        input.close();

        System.out.println("The word was " + randWord + ", you guessed it in " + " moves!");

    }

generateWord方法:

public static void generateWord(){

    randWord = WORD_LIST[(int)(Math.random() * 87)];

    for(int i = 0; i < randWord.length(); i++){

        guessWord = guessWord + "_ ";

    }

    for(int i = 0; i < randWord.length(); i++){

        randWordExt = randWordExt + randWord.charAt(i) + " ";

    }

}

最后是guessLetter方法:

public static void guessLetter(char letter){

    boolean changed = false;

    for(int i = 0; i < randWordExt.length(); i++){

        if(!(guessWord.charAt(i) == letter)){

            if(randWordExt.charAt(i) == letter){

                guessWord = guessWord.substring(0, i) + letter + guessWord.substring(i + 1);
                changed = true;

            } else if (randWordExt.charAt(i) != letter && i == randWordExt.length() - 1 && changed == false){

                LIVES -= 1;
                System.out.println("\'" + letter + "\'" + " is not in the word!");

            }

        } else {

            System.out.println("\'" + letter + "\'" + "has already been guessed!");

        }

    }

}

0 个答案:

没有答案