0

I am writing a program where the user enters a number and the computer guesses the number.

I'm having trouble with my else/if statement inside of my while loop. The problem is it prints out "guess higher" but the computer does not always guess higher. I'm not sure how to go about this problem.

while(computerGuess != userGuess) {
    if(computerGuess > userGuess) {
        System.out.println("Guess lower: ");
        computerGuess = guess.nextInt(userGuess);
        System.out.println(computerGuess);
    }else if(computerGuess < userGuess) {
        System.out.println("Guess higher: ");
        computerGuess = guess.nextInt(101);
        System.out.println(computerGuess);
    }
    amountTries++;
}
  • 4
    Provide a [mcve]. – RaminS Oct 04 '17 at 18:04
  • 2
    Is the `guess` variable a `java.util.Random`? –  Oct 04 '17 at 18:05
  • 1
    If you're using `java.util.Random`, then [take a look at javadoc](https://docs.oracle.com/javase/8/docs/api/java/util/Random.html#nextInt-int-). `nextInt(101)` will return a random number between 0 and 100 - it's **not** guaranteed to be higher than the previous one. –  Oct 04 '17 at 18:10
  • `guess.nextInt(userGuess)` ... that's a bit unfair for the PC, cause it can never guess the correct number with that line. `guess.nextInt(101)` That needs and offset and is it guaranteed, that the users number is lower than 101? – Tom Oct 04 '17 at 18:12
  • Possible duplicate of [How do I generate random integers within a specific range in Java?](https://stackoverflow.com/questions/363681/how-do-i-generate-random-integers-within-a-specific-range-in-java) –  Oct 04 '17 at 18:12

2 Answers2

1

The problem is it prints out "guess higher" but the computer does not always guess higher. I'm not sure how to go about this problem.

You are specifying a hard-coded limit of 101 for the random number generation. But in the case where the computer guess is smaller than the user value, you need to have a random number generated between the computer guess and the user guess.

Replace

computerGuess = guess.nextInt(101);

with

computerGuess = guess.nextInt(userGuess - computerGuess) + computerGuess + 1;

VHS
  • 9,534
  • 3
  • 19
  • 43
0

If you are trying to build a program where computer guesses the number by binary search logic then your code is not going to work. Following code will perform binary search kind of logic.

int i=0;int j=101;
while(computerGuess != userGuess) {

    if(computerGuess > userGuess) {
        j=computerGuess;
        System.out.println("Guess lower: ");
        computerGuess = guess.nextInt(j);
        System.out.println(computerGuess);
    }else if(computerGuess < userGuess) {
        i=computerGuess;
        System.out.println("Guess higher: ");
        //computerGuess = guess.nextInt(101);
        computerGuess = guess.nextInt(j - i) +i;
        System.out.println(computerGuess);
    }
    amountTries++;
}

PS: Not tested for corner cases. Code is just to provide a basic idea.