【问题标题】:Cannot quit this loop?无法退出此循环?
【发布时间】:2018-10-28 19:00:32
【问题描述】:

我写了一个使用while循环的简单猜谜游戏。 如果用户输入任何首字母为“y”的单词,游戏将重新运行,但如果用户输入任何其他单词,游戏将退出并给出报告。

public static void loopcalc(Scanner console) {
  int totalRounds = 0, totalGuesses = 0, best = 1000000;
  boolean want = true;

  while (want = true) {
    int eachguess = playOneGame(console);
    totalRounds++;
    totalGuesses += eachguess;

    System.out.println("Do you want to play again?");
    String input = console.next();

    if (input.toLowerCase().charAt(0) == 'y') {
      want = true;
    } else {
      want = false;
    }
    best = Math.min(eachguess, best);
  }
  report(console, totalGuesses, totalRounds, best);
}

对不起,我不知道如何正确输入代码。

【问题讨论】:

    标签: java loops while-loop


    【解决方案1】:

    你写道:

    while(want = true) {
    

    您肯定想检查want 是否为true。所以改写:

    while(want == true) {
    

    或者,更好:

    while(want) {
    

    在 Java 中,= 是一个为变量赋值的运算符。它还返回值。所以,当你输入wanted = true 时,你:

    • want 设置为true
    • 返回true

    这里,while 返回得到true,然后无限继续循环。

    Ps:这是一个非常常见的问题。 2003年,一个famous attempt在Linux内核中插入后门就使用了这个特性(C语言也有)。

    【讨论】:

    • 我添加了一个解释。顺便感谢@Joakim Danielson 修复了一个错字。
    【解决方案2】:

    这是您的最新答案。

    public static void loopcalc(Scanner console) {
      int totalRounds = 0, totalGuesses = 0, best = 1000000;
      boolean want = true;
    
      while (want) {
        int eachguess = playOneGame(console);
        totalRounds++;
        totalGuesses += eachguess;
    
        System.out.println("Do you want to play again?");
        String input = console.next();
    
        if (input.toLowerCase().charAt(0) == 'y') {
          want = true;
        } else {
          want = false;
        }
        best = Math.min(eachguess, best);
      }
      report(console, totalGuesses, totalRounds, best);
    }
    

    您也可以尝试以下方法并摆脱想要的变量:

    public static void loopcalc(Scanner console) {
    int totalRounds = 0, totalGuesses = 0, best = 1000000;
    boolean want = true;
    
    while (true) {
    int eachguess = playOneGame(console);
    totalRounds++;
    totalGuesses += eachguess;
    
    System.out.println("Do you want to play again?");
    String input = console.next();
    
    if (input.toLowerCase().charAt(0) == 'n') {
      break;
    }
    best = Math.min(eachguess, best);
    }
    report(console, totalGuesses, totalRounds, best);
    }
    

    【讨论】:

      【解决方案3】:

      want = true 中的= 是一个赋值运算符。您应该尝试的是相等 == 运算符。

      while(want == true)while(want)

      【讨论】:

        猜你喜欢
        • 2020-11-23
        • 2020-06-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-03-18
        • 1970-01-01
        • 2023-03-12
        相关资源
        最近更新 更多