简体   繁体   中英

While loops having trouble

I have tried my code like below..

public class GuessNumber {

    public static void main(String[] args) {

        Scanner scan = new Scanner(System.in);

        Random rand = new Random();

        int number = rand.nextInt(100) + 1;

        int guess;

        System.out.println("Guess the number between 1 and 100");
        System.out.println("");

        guess = scan.nextInt();

        while (guess < number) {
            System.out.println("Higher!");
            guess = scan.nextInt();
        }
        while (guess > number) {
            System.out.println("Lower!");
            guess = scan.nextInt();
        }
        while (guess == number) {
            System.out.println("Correct!");
            break;
        }
    }
}

and I'm having trouble making it ask until the user gets the right number. And at the end for the game to ask if the user wants to play the game again

Your use of loops here

while (guess < number) {
    System.out.println("Higher!");
    guess = scan.nextInt();
}
while (guess > number) {
    System.out.println("Lower!");
    guess = scan.nextInt();
}
while (guess == number) {
    System.out.println("Correct!");
    break;
}

is creative . It happens to be flawed, but it's very creative. You need something like

while (guess != number) {
  System.out.println((guess < number) ? "Higher!" : "Lower!");
  guess = scan.nextInt();
}
System.out.println("Correct!");

you need only a single while loop. rearrange your logic in your loop.

boolean isRunning = true;

while(isRunning){

guess = scan.nextInt();

if(guess < number){
  System.out.println("Higher!");
}else if(guess > number){
  System.out.println("Lower!");
}else if(guess == number){
  System.out.println("Correct!");
//ask if need another input. (want to continue or not)
 if(not continue){
    break; or isRunning = false;
 }

}


}

The logic is not quite right. You want one while loop to check each condition and continue asking for a new number while the guess does not equal the number.

while (guess != number) {
  if (guess < number)
    System.out.println("Higher!");
  else
    System.out.println("Lower!");
  guess = scan.nextInt();
}
System.out.println("Correct!");
while (true) {
     if(guess < number)       
        System.out.println("Higher!");
     else if(guess > number)
        System.out.println("Lower!");
     else if (guess == number){
        System.out.println("Correct!");
     }
     guess = scan.nextInt();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM