Write a program that generates a random number between 1 and 10 and asks the use
ID: 3733034 • Letter: W
Question
Write a program that generates a random number between 1 and 10 and asks the user to guess what the number is. Your program should operate similar to mine, who's output is shown below: s java Labs enter a number between 1 and 10: 5 Your guess of 5 is too low. enter a number between 1 and 10:7 Your guess of 7 is too high. enter a number between 1 and 10: 6 Your guess of 6 is CORRECT! Your guesses were: 5 7 6 Your program should give the user a maximum of five guesses. After five guesses, the program should display a message and exit as shown below: s java Lab5 enter a number between 1 and 10:5 Your guess of 5 is too low. enter a number between 1 and 10:4 Your guess of 4 is too low. enter a number between 1 and 10: 3 Your guess of 3 is too low. enter a number between 1 and 10:2 Your guess of 2 is too low. enter a number between 1 and 10: 1 Your guess of 1 is too low. Better luck next time! (a particularly unskilled player!) Your guesses were: 5 4 3 2 1 Note in both sets of output that the program keeps track of the guesses as the user makes them and then displays the guesses at the end of the game. To keep your program as simple as possible at first, wait and add this feature on after you have the basic game functioning.Explanation / Answer
import java.util.Random;//package where random fuction available
import java.util.Scanner;//package where random fuction available
public class GenerateRandom{
public static void main(String args[])
{
Random rand = new Random();//used to generate random number
Scanner s=new Scanner(System.in);
Random r = new Random();
int Low = 1,High = 10,Result,i=1;
int ar[]=new int[5];
Result= r.nextInt(High-Low) + Low;//to get the number in between range
while(i!=6)
{
System.out.print("enter number between 1 and 10:");
int guess=s.nextInt();
ar[i-1]=guess;
if(guess==Result)
{ System.out.println("your guess of "+guess+ " is CORRECT!");
break;}
else if(guess<Result)
System.out.println("your guess of "+guess+" is too low");
else if(guess>Result)
System.out.println("your guess of "+guess+" is too high");
else if(i==5)
{
System.out.println("Better luck next time!");
break;
}
i++;
}
int j=0;
System.out.print("Your guesses were: ");
while (j!=i)//printing guesses
{
System.out.print(" "+ar[j]+" ");
j++;
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.