Within the NumberGuesser program, I have to include an extended class called RandomNumberGuesser that simply generates a random initial number to the user when the first guess is displayed. The random number should generate and somehow be stored as the initial number guessed. Here are my classes and the demo program:
public class Number__Guesser {
protected int high;
protected int low;
protected int lower;
protected int higher;
public Number__Guesser(int lowerBound, int upperBound) {
low = lower = lowerBound;
high = higher = upperBound;
}
public int getCurrentGuess() {
return (high + low) / 2;
}
public void higher() {
low = getCurrentGuess() + 1;
}
public void lower() {
high = getCurrentGuess() - 1;
}
public void reset() {
low = lower;
high = higher;
}
}
The class that I need assistance with:
import java.util.Random;
public class RandomNumberGuesser extends Number__Guesser{
protected int number;
protected int high;
protected int low;
protected int lower;
protected int higher;
public RandomNumberGuesser(int lowerBound, int upperBound)
{
super(lowerBound, upperBound);
low = lower = lowerBound;
high = higher = upperBound;
}
public void setCurrentGuess(int n)
{
number = n;
}
public int getCurrentGuess()
{
Random randomNumbers = new Random();
number = low + randomNumbers.nextInt(high);
return number;
}
}
The program that puts it all together, without the RandomNumberGuesser extensions:
import java.util.*;
public class Guessing__Program
{
public static void main(String[] args)
{
int lowerBound = 1;
int upperBound = 100;
Number__Guesser guesser = new Number__Guesser(lowerBound, upperBound);
char response;
do {
guesser.reset();
System.out.println("Think of a number from " + lowerBound + " to " + upperBound + ".");
do {
response = promptUserAndGetResponse(guesser.getCurrentGuess());
if (response == 'h') guesser.higher();
if (response == 'l') guesser.lower();
if (response == 'r') guesser.reset();
} while (response != 'c');
} while (shouldPlayAgain());
}
public static char promptUserAndGetResponse(int guess) {
char response;
Scanner input = new Scanner(System.in);
do {
System.out.print("Is it " + guess + "? (h/l/c): ");
response = input.next().charAt(0);
} while (response != 'h' && response != 'l' && response != 'c' && response != 'r');
return response;
}
public static boolean shouldPlayAgain() {
char response;
Scanner input = new Scanner(System.in);
do {
System.out.print("Do you want to play again? (y/n): ");
response = input.next().charAt(0);
} while (response != 'y' && response != 'n');
return response == 'y';
}
}
When I apply the RandomNumberGuesser class I generate a random number and continuously generate another random number. Not sure how to store the number and only have the random number called for the initial guess. Any help would be appreciated.
Aucun commentaire:
Enregistrer un commentaire