In this program, the user has to think of a number and let the computer to guess it.
The computer will ask the user for the bound,
The computer will guess the number between the bound,
The user will type in "higher" or "lower" to lead the computer to guess the correct number,
If the computer guesses the right answer, the user will input "yes", and print a correct statement.
The coding below is what I am working on, However, I got stuck in some problems. Please help me out! Thank you!
Problems that I found:
1. I do not understand how to define the randomInt function inside the class, but outside the main function.
2. I tried the program but the computer's guess is weird. The computer won't guess a number that based on my guide.
public class Guess
{
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
Random rand = new Random();
//ask about the lower bound,
TextIO.putln("Hey there! Welcom to the game!\n"
+ "I'm going to guess a number, and you have to pick it\n"
+ "and you get to decide the bounds.\n" +
"What should the lower bound be?");
int lowerlimit = TextIO.getInt();
//if the user enter the number lower than 0,
while ((lowerlimit < 0))
{
TextIO.putln("ERROR Please enter a number that greater than 0");
lowerlimit = TextIO.getInt();
}
//ask about the upper bound,
TextIO.putln("Great! How about the upper bound?");
int upperlimit = TextIO.getInt();
//if the user enter the number lower than 0,
while ((upperlimit <= lowerlimit))
{
TextIO.putln("ERROR Please enter a number "
+ "that greater than the lower bound.");
upperlimit = TextIO.getInt();
}
//Print the range and instruction,
TextIO.putln("Ok. In the range between " + lowerlimit +
" and " + upperlimit + ":" + "\nPlease enter 'lower'/'higher' "
+ "when the number I picked is not correct\n"
+ "Enter 'yes' when I picked the right number"
);
//Generate the random number between the range,
int randNum = (int) ((Math.random() * ((upperlimit - lowerlimit) + 1)) + lowerlimit);
String feedback = "";
while (!feedback.equals("yes"))
{
TextIO.putln("I think it is " + randNum);
feedback = in.nextLine();
//When the computer need to pick a lower number,
if (feedback.equals("lower"))
{
upperlimit = randNum - 1;
randNum = (int) ((Math.random() * ((upperlimit - lowerlimit) + 1)) + lowerlimit);
}
//When the computer need to pick a higher number,
else if (feedback.equals("higher"))
{
lowerlimit = randNum + 1;
randNum = (int) ((Math.random() * ((upperlimit - lowerlimit) + 1)) + lowerlimit);
}
}
{
//When the user guesses the correct number,
TextIO.putln("Yes! Correct!:)");
}
in.close();
}
public static int randomInt(int min, int max) {
return (int) ((Math.random() * ((max - min) + 1)) + min);
}
} // end of Guess class