簡體   English   中英

While循環永遠重復打印語句時

[英]While Loop Repeating forever when printing statement

我正在制作一個Hangman游戲,用戶可以猜測一種顏色。 我想發生的事情是:如果用戶錯誤地獲得了5個以上的錯誤(通過所有5條提示),它將表明該用戶已丟失。 while循環結束后(單詞正確或經過所有5條提示),它應該告訴您是否獲勝。 這是執行此操作的代碼部分:

public static void main(String[] args){
  Scanner in = new Scanner(System.in);
  String color = getColor();
  String result = EmptyStr(color);
  String[] hints = getHints(color);
  System.out.println("Please enter a letter:");
  char letter = in.next().charAt(0);
//-----------------------------------------------------------
  int wrong = 0;
  while (wrong<6){
    if (checkLetter(color, letter)){
      // result was previously defined elsewhere so don't worry about it
      result = Result(color, result, letter);
      System.out.println("Correct guess! here is your word so far: " + result);
      System.out.println("Lifelines left: " + (5 - wrong));
      if (result.equals(color)){
        System.out.println("congratulations! You Won!");
        break;
      }
    }
    else{
      wrong ++;
      System.out.println(hints[0]);
      System.out.println("Lifelines left: " + (5 - wrong));
    }
  }
  // also not sure what to put here after player wins or loses: System.out.println("Sorry! You lost! The correct word was: " + color);

}

但是,一旦我輸入了一個字母並且正確無誤, result = Result(color, result, letter); System.out.println("Correct guess! here is your word so far: " + result); System.out.println("Lifelines left: " + (5 - wrong)); result = Result(color, result, letter); System.out.println("Correct guess! here is your word so far: " + result); System.out.println("Lifelines left: " + (5 - wrong)); 永遠重復。 我想知道:為什么它會永遠重復? 而且,我該如何對其進行修復?

我發現了自己的問題!

問題是,為了重申它並允許我重新輸入一個字母, char letter = in.next().charAt(0); 必須在while循環內。 這解決了整個問題!

我想我看到了問題。 當用戶正確猜對時,沒有迭代,只有在錯誤猜對時才有迭代。 確保首先添加另一個“錯誤的++”。 那可能會解決問題。

if (checkLetter(color, letter)){
      // result was previously defined elsewhere so don't worry about it
      result = Result(color, result, letter);
      System.out.println("Correct guess! here is your word so far: " + result);
      System.out.println("Lifelines left: " + (5 - wrong));
      wrong ++;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM