猜猜游戏,循环错误

时间:2016-02-23 06:40:02

标签: java performance

我在猜测游戏时遇到以下代码问题,范围设置为1-32。它启动了,但是一旦我做出第一次猜测,我就会给出太高或太低,加上正确的答案。所以我总能在2次猜测中得到正确的答案,这是不可能的。我想我的while循环有问题。

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

1 个答案:

答案 0 :(得分:1)

移动

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

进入你的状况:

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

否则,它将被无条件地调用 - 意味着在循环的每次迭代中。或者,您可以在while循环后打印它,因为游戏已在那里完成。

相关问题