Zhong Zhiwei
Zhong Zhiwei

Reputation: 21

Cannot quit this loop?

I wrote a simple guessing game which uses while loop. If user types any word with an initial of "y", the game will run again, but if user types any other word, the game will quit and gives out the report.

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);
}

Sorry I do not know how to type codes correctly.

Upvotes: 2

Views: 87

Answers (3)

potato
potato

Reputation: 4589

= in want = true is an assignment operator. What you should try instead is the equality == operator.

while(want == true) or while(want)

Upvotes: 0

Gauravsa
Gauravsa

Reputation: 6514

This is your updated answer.

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);
}

You can also try following approach and get rid of want variable:

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);
}

Upvotes: 0

Amessihel
Amessihel

Reputation: 6364

You wrote:

while(want = true) {

You surely want to check if want is true. So write instead:

while(want == true) {

Or, better:

while(want) {

In Java, = is an operator which assigns a value to a variable. It returns also the value. So, when you type wanted = true, you:

  • Set want to true
  • Return true

Here, while returns gets true, and continue the loop infinitely.

Ps : this is a very frequent issue. In 2003, a famous attempt to insert a backdoor in the Linux kernel used this feature (C language has it too).

Upvotes: 6

Related Questions