为什么我的while循环继续?

时间:2017-03-28 08:12:50

标签: java do-while

我试图为学校做一个简单的Hangman游戏。

在开始时,用户将一个单词作为String输入,并将该字符串转换为char数组,wordArray。然后创建一个char数组starArray,它与wordArray具有相同数量的元素,并用" *"填充。正确猜出字母后,这些开头会被字母替换。

在此之后,我有了这个循环:

do {
    System.out.println("Guess a letter:");
    strGuess = scan.nextLine();
    chGuess = strGuess.charAt(0); 
    //prompts the user to guess a letter and converts said letter to a char

            for(int i = 0; i<Array.getLength(wordArray); i++){
                if (chGuess == wordArray[i]){
                     starArray[i] = strGuess.charAt(0);
                     guessCorrect = true;
                    }
            }   //this happens if the guess is correct

            if (guessCorrect == false){
                System.out.println("Nope, wrong guess!");
                 wrongGuess = wrongGuess + 1;
                 System.out.println("You have " + (5-wrongGuess) + " lives left.");
            } //if the guess isn't correct, amount of wrong guesses increases

            guessCorrect = false; //the value of whether a guess is correct resets

            for(int i=0;i<starArray.length;i++){
                System.out.print(starArray[i]);
            } //prints out the word with "*" in place of letters that haven't been guessed yet

           /*if starArray == wordArray
            wordGuessed = true;*/

    } while (wrongGuess == 5 || wordGuessed == false); //if the word is guessed or the user has guessed wrong 5 times, the loop ends

现在这段代码还没有完成,所以&#34; wordGuessed&#34;部分状况永远不会发生 - 现在你还无法赢得比赛。但是,当wrongGuess值高于5时,循环不会结束。它将继续运行,提示用户反复猜测。我检查过,并且wordGuessed值实际上确实正确地改变了,在5次错误的猜测之后确实达到了5。

1 个答案:

答案 0 :(得分:2)

如果wordGuessed始终为false,则wordGuessed == false将始终返回true。

循环的条件是wrongGuess == 5 || wordGuessed == false为真。 使用第一个语句,可以替换为:wrongGuess == 5 || true

anything OR true为真时,这也将永远为真。

您希望停止循环一次wrongGuess == 5wordGuessed == true)。 换句话说,循环 !((wrongGuess == 5) OR (wordGuessed == true))

基本布尔代数, A OR B 的反面是!A AND!B 。你必须在wrongGuess != 5 && wordGuessed == false

时保持循环