Reputation: 19
import java.util.Scanner;
import java.util.Random;
public class GuessHarder {
public static void main(String[] args) {
Random generator = new Random();
Scanner reader = new Scanner(System.in);
String higher = "higher", lower = "lower", correct = "correct", input;
int guess, random, random2 = 1, random3 = 100, randomLast, cntr = 1;
random = generator.nextInt(100) + 1;
randomLast = random;
System.out.println("Is your number: " + random);
System.out.println("Input if number should be higher, lower, or correct: ");
input = reader.next();
while (!input.equals("correct")){
if (input.equals("lower")){
randomLast = random2;
random2 = generator.nextInt(100) + 1;
if ((random2 < random) && (random2 < randomLast)){
random = random2;
cntr += 1;
System.out.println("Is your number: " + random);
System.out.println("Input if number should be higher, lower, or correct: ");
input = reader.next();
} else {
input = lower;
}
} else if (input.equals("higher")){
randomLast = random3;
random3 = generator.nextInt(100) + 1;
if ((random3 > random) && (random3 > randomLast)){
random = random3;
cntr += 1;
System.out.println("Is your number: " + random);
System.out.println("Input if number should be higher, lower, or correct: ");
input = reader.next();
} else {
input = higher;
}
}
}
System.out.println("Computer took " + cntr + " amount of tries to guess your number");
}
}
When I input higher or lower it will give me the number higher or lower than the previous respectively but it won't remember previous numbers. For clarity an example would be:
"Is your number: 65
Input if number should be higher, lower, or correct:
higher
Is your number: 96
Input if number should be higher, lower, or correct:
lower
Is your number: 59
Input if number should be higher, lower, or correct:"
The range by the last input should have been 65-96, but instead it just does 0-96 so I get numbers like 59 that shouldn't be in the range. What should I change to set it up to remember last two inputs for range instead of just the last.
Upvotes: 0
Views: 7548
Reputation: 7824
So keep two variables that "remember" the lower and upper bounds.
int lowerBound = 0;
int upperBound = MAX_NUMBER;
Then each time the computer makes a guess you need to update these two numbers.
Once you update the two numbers you need to generate a new guess based on those numbers.
generator.nextInt(upperBound - lowerBound + 1) + lowerBound;
The +1
makes the value inclusive.
Upvotes: 4
Reputation: 2525
You have to remember the lower and the upper bound and try to make a random number between them instead of
generator.nextInt(100) + 1;
Upvotes: 2