在打印语句

时间:2017-11-08 04:10:51

标签: java while-loop java.util.scanner

我正在制作一个用户猜猜颜色的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)); 永远重复。我想知道:为什么它会永远重复?而且,我该如何解决它才能起作用?

2 个答案:

答案 0 :(得分:0)

我发现了自己的问题!

事情是,为了重申并允许我重新输入一封信,      char letter = in.next().charAt(0); 必须在while循环中。这解决了整个问题!

答案 1 :(得分:-1)

我想我看到了这个问题。当用户得到正确的猜测时,您没有迭代,只有在错误的时候。确保在第一个if中添加另一个“错误的++”。这可能会解决问题。

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 ++;