Reverse Number guessing game

• April 22nd, 2011, 11:39 PM
rarman555
Reverse Number guessing game
I call this a reverse number guessing game because usually the computer would generate a number for you to guess, but I want the computer to guess my number by guessing randomly in decreasing ranges depending on if I say too high or too low.

The biggest problem I'm having is making the range of the random number be correct. It likes to guess numbers out of the range.

The computer starts off by giving me a number from 1 - 100. Then i type in "th", "tl", or "co" (too high, too low, correct).

If I say too low the lowest number in the range should change to the previous guess and same for if i say too high (but it gets set to the previous highest number instead of previous lowest).

This should decrease the range of the random generator until it gets to the point where the range is so small that the computer can only guess my number or it might just get lucky before that (just like a human).

Here's the code:
Code :

```import java.util.*;   public class computer_guess { public static void main(String[] args) { Scanner console; console = new Scanner(System.in); Random aRandom = new Random();   int prev_low = 1, prev_high = 100, guess = aRandom.nextInt(prev_high) + prev_low, guesses = 0;     // long time = 0;   boolean win = false;   String feedback;       while(!win) { System.out.println("My guess is: " + guess); feedback = console.nextLine(); //   if(feedback.equals("tl") || feedback.equals("th") || feedback.equals("co")) { if(feedback.equals("tl"))//too low { prev_low = guess; System.out.println(feedback); } else if(feedback.equals("th"))//too high {   prev_high = guess; System.out.println(feedback); } else if(feedback.equals("co"))//correct { System.out.print("Yay, I WIN!"); win = true; System.out.println(feedback); }   guess = aRandom.nextInt(prev_high) + prev_low; //++guesses; //feedback = " "; //System.out.print(feedback); } } } }```
• April 23rd, 2011, 12:40 AM
helloworld922
Re: Reverse Number guessing game
You're generating a random number in the range of [prev_low, prev_low+prev_high). To generate one in the correct range, pass the difference between the high and low values to nextInt()
• April 23rd, 2011, 02:18 AM
rarman555
Re: Reverse Number guessing game
wow lol that was easy thanks!
• April 23rd, 2011, 10:18 AM
copeg
Re: Reverse Number guessing game
This thread has been cross posted here: