简体   繁体   中英

Guessing Game, loop error

I'm having a problem with the following code for a guessing game, range set for 1-32. It starts up, but once I take my first guess, I'm given either Too High or Too Low,plus the correct answer. So I'm always able to get the correct answer in 2 guesses, which isn't suppose to happen. I think I have a problem with the while loop.

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

public class GuessingGame1 {

public static void main(String[] args) {

    /*
     * Following should create a random number
     * Generated by computer between 0-32
     */
    Random rng = new Random ();
    int value = rng.nextInt(32);
    int numberOfTries = 0;

    Scanner input = new Scanner (System.in);
    int guess = 0;
    boolean win = false;
    while (win == false) {


    System.out.println("Guess of a Number between 1-32, I will tell you \n " +
                        "if your guess is too high, too low, or correct!");

        /*
         * Uses makes a guess and program tells if the guess is correct,
         * too high, or too low.
         */

    System.out.println("Enter your guess: ");
    guess = input.nextInt();
    numberOfTries++;

    if (guess == value){
        win = true;

    }   else if (guess > value){
        System.out.println("Your guess is too high, try again");

    } else if (guess < value){
        System.out.println("Your guess is too low, try again");


    }
    System.out.println("Yes, the number is " + value);
    System.out.println("It took you " + numberOfTries + " tries");
  }
 }
}

Move

System.out.println("Yes, the number is " + value);
System.out.println("It took you " + numberOfTries + " tries");

into your condition here:

if (guess == value){
    win = true;
}

Otherwise, it will be called unconditionally - meaning in every iteration of the loop. Alternatively, you can print it after your while loop, as the game is finished there.

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