Generate a random number in [0, 100] in java. Write an efficient guess procedure
ID: 3939384 • Letter: G
Question
Generate a random number in [0, 100] in java. Write an efficient guess procedure that takes no more than 7 guesses to get any given integer in that range. For each guess, the hint can be one of the following:
-Congratulations! You got it.
-The guess is too large.
-The guess is too small.
Here is a sample output:
Guess #1: 50
The guess is too big.
Guess #2: 24
The guess is too small.
Guess #3: 37
The guess is too big.
Guess #4: 30
The guess is too small.
Guess #5: 33
The guess is too big.
Guess #6: 31
The guess is too small.
Guess #7: 32
Congratulations!
What if the random number is in [0, 1000], how many guesses your program will take?
Explanation / Answer
//Note : This Programme takes no more than 7 guesses to find random number if range between 0,100
//Note : This Programme takes no more than 11 guesses to find random number if range between 0,1000
//Random Number Guess Programme if range 0,100
//RAndom Number Guess Programme
import java.util.Scanner; //scanner class to read data
import java.util.Random; //random class to generate random number
public class Guess //create class Guess
{
public static void main(String []args) //define main method
{
int gvalue;
Scanner sc=new Scanner(System.in); //create scanner object
Random r = new Random(); //create random object
int Low = 0;
int High = 1000;
int Result = r.nextInt(High-Low) + Low; //generate rand between 0,100
//System.out.println(Result);
int i=0;
while(true) //loop check for only 7 guesses
{
System.out.println("Guess #"+(i+1)); //prompt for value for each guess
gvalue=sc.nextInt(); //read guessing value
if(gvalue<Result) //check guess value is small or grater or equal to random number by if else ladder
System.out.println("The guess is too small.");
else if(gvalue>Result)
System.out.println("The guess is too large.");
else
{
System.out.println("Congratulations! You got it.");
break;
}
i++;
}
}
}
Output :
Guess #1
50
The guess is too small.
Guess #2
75
The guess is too small.
Guess #3
87
The guess is too large.
Guess #4
81
Congratulations! You got it.
Output 2 (If range between 0,1000): for running change value
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.