Reputation: 37
I am creating a simple game where a random number is generated and if you guess right you win! My problem: There is a while loop (run) to keep running the game until a player decides to quit. When the player selects quit, the loop is supposed to be set to false and stop, but when a player hits quit, the program repeats the loop. The part of the program where the boolean is set to false is bolded.
import java.util.Scanner;
import java.util.Random;
public class RunHiLowGame {
public static void main(String[] args) {
// TODO Auto-generated method stub
//variables
String name;
int guess;
int guessnum = 0;
boolean run = true;
int number;
int choice;
Scanner input = new Scanner(System.in);
Random r = new Random();
number = 1;
//welcome
//create loop to ask guess then check if high or low
while (run = true) {
//enter guess
System.out.println("Enter your guess:");
guess = input.nextInt();
//if low say press 1 to retry
if (guess > 0 && guess < 100) {
if (guess < number) {
System.out.println("Your number was too low! Guess again!");
guessnum++;
}
else if (guess > number) {
System.out.println("Your number was too high! Guess again!");
guessnum++;
}
else if (guess == number) {
System.out.println("You have won!");
guessnum++;
System.out.println("Amount of guesses:" + guessnum );
System.out.println("Press 1 to play again or press 2 to exit the game.");
choice = input.nextInt();
if (choice == 1) {
System.out.println("Restarting.\n");
}
else if (choice == 2) {
System.out.println("Exiting.");
run = false
}
else {
System.out.println("Error.");
}
}
else {
System.out.println("Invalid answer.");
}
}
}
System.out.println("Exited.");
}
}
Upvotes: 0
Views: 13901
Reputation: 301
I think you should replace "run = false" with "System.exit(0);".
I think the loop is self-contradictory because it works only if run is true. Once run is false, the loop doesn't work and run therefore isn't false. To test this, write this code after pressing quit: System.out.println (run ? "Run is true" : "Run is false").
Upvotes: 0
Reputation: 1742
The operator for checking equality is ==
. Your expression for the while
loop, run = true
, assigns true
to run
.
Upvotes: 0
Reputation: 201429
You have a single =
when you need two here
while(run = true)
with one, it's assignment (which also yields the value assigned in Java). Something like,
while(run == true)
you can also use the simpler
while (run)
Upvotes: 6