简体   繁体   中英

while loop in java number guess

So I've been working on this and it works fine, only problem is that after you guess a number that's not between 1 and 100, it goes onto the next guess when the try shouldn't count against you. I've attached a picture of what the output SHOULD look like.

Do I need a 'for' statement or a boolean variable?

在此处输入图片说明

And here is my code:

Random generator = new Random();

//import the scanner for prompt
Scanner input = new Scanner(System.in);

//integers for the secret number, input guess of the secret number, tries and limit to tries
int numberToGuess = 1 + generator.nextInt(100);
int numberOfTries = 1;
int limit = 10;
int guess;

//prompt user to enter a number to guess
System.out.println("You have 10 tries to guess a number between 1 and 100");

//start of while loop
while (numberOfTries <= 10) {
    System.out.print("Guess number " + numberOfTries + ": ");
    guess = input.nextInt();
    //if else statements (outputs)
    if (guess < numberToGuess)
        System.out.println("Your guess is too low. Try again.");
    else if (guess > 100)
        System.out.println("Guesses should be between 1 and 100.");
    else if (guess > numberToGuess)
        System.out.println("Too high. Try again.");
    else if (guess == numberToGuess) {
        System.out.println("Congratulations! You have correctly guess the number in " + numberOfTries + " tries");
        System.exit(0);
    } else {
        System.out.println("Sorry, you did not guess the guess the answer in 10 tries");
        System.out.println("The number was " + numberToGuess);

        //break to end while loop
        break;
    }
    numberOfTries++;

    // If statement after executing the while loop the output if user loses and answer to secret number
    if (numberOfTries > 10) {
        System.out.println("Sorry, you did not guess the guess the answer in 10 tries");
        System.out.println("The number was " + numberToGuess);
    }
}

Don't increment numberOfTries++; if they guess a number outside of the range. Put the increment inside the if statements

Try using a nested do-while loop inside your primary while loop:

//start of while loop
while(numberOfTries <= 10){
    //get a valid guess
    do{
        boolean valid = true;
        System.out.print("Guess number " + numberOfTries + ": ");
        guess= input.nextInt();
        //if else statements (outputs)
        if (guess < numberToGuess){
             System.out.println("Your guess is too low. Try again.");
             valid = false;
        }
        else if (guess > 100){
            System.out.println("Guesses should be between 1 and 100.");
            valid = false;
        }
    while (!valid);

    //handle the valid guess

}

Here's how I'd do it. You tell me which one you prefer:

import java.util.Random;
import java.util.Scanner;

/**
 * Created by Michael
 * Creation date 3/4/2016.
 * @link https://stackoverflow.com/questions/35809392/while-loop-in-java-number-guess
 */
public class NumberGuess {

    public static final int MIN_VALUE = 1;
    public static final int MAX_VALUE = 100;
    public static final int MAX_TRIES = 10;

    public static void main(String[] args) {
        Random generator = new Random();
        Scanner input = new Scanner(System.in);
        String playAgain;
        do {
            int answer = MIN_VALUE + generator.nextInt(MAX_VALUE);
            System.out.println(String.format("You have %d tries to guess a number between %d and %d", MAX_TRIES, MIN_VALUE, MAX_VALUE));
            boolean correct = playGuessingGame(input, answer);
            if (!correct) {
                System.out.println(String.format("The number was %d", answer));
            }
            System.out.print("Play again? [Y/N]: ");
            playAgain = input.nextLine();
        } while ("Y".equalsIgnoreCase(playAgain));
    }

    public static boolean playGuessingGame(Scanner input, int answer) {
        boolean correct = false;
        int numTries = 0;
        do {
            System.out.print(String.format("Guess %d: ", ++numTries));
            int guess = Integer.parseInt(input.nextLine());
            if (guess < MIN_VALUE) {
                System.out.println(String.format("Guess %d is below minimum %d", guess, MIN_VALUE));
            } else if (guess > MAX_VALUE) {
                System.out.println(String.format("Guess %d is above maximum %d", guess, MAX_VALUE));
            } else if (guess < answer) {
                System.out.println(String.format("Guess %d is too low. Try again.", guess));
            } else if (guess > answer) {
                System.out.println(String.format("Guess %d is too high. Try again.", guess));
            } else {
                System.out.println("Woo hoo!  You got it right!");
                correct = true;
                break;
            }
        } while (numTries < MAX_TRIES);
        return correct;
    }
}

You and your professor realize that it's almost impossible to lose this game. Right?

A bisection strategy says you can always get the right answer with 10 tries. Make that number smaller for a challenge.

应该在if statemnt:D内部完成

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