不能退出这个循环?

Zho*_*wei 2 java loops while-loop

我写了一个使用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);
}
Run Code Online (Sandbox Code Playgroud)

抱歉,我不知道如何正确输入密码.

Ame*_*hel 6

你写了:

while(want = true) {
Run Code Online (Sandbox Code Playgroud)

你一定要检查是否wanttrue.所以写一下:

while(want == true) {
Run Code Online (Sandbox Code Playgroud)

或更好:

while(want) {
Run Code Online (Sandbox Code Playgroud)

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

  • 设置wanttrue
  • 返回 true

这里,while返回获取true并无限循环.

Ps:这是一个非常频繁的问题.在2003年,一个着名的尝试在Linux内核中插入后门使用了这个功能(C语言也有它).