Write a program that generates a random number between 1 and 10 and asks the use
ID: 3733382 • 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: ========================================================= $ java Lab5 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: ========================================================= $ 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. (a particularly unskilled player!) 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! 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
Lab5.java
import java.util.Random;
import java.util.Scanner;
public class Lab5 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
Random r = new Random();
int rand = r.nextInt(10)+1;
int n;
String s = "";
System.out.println("enter a number between 1 and 10: ");
n = scan.nextInt();
int count = 1;
while(n != rand && count<=5) {
count++;
s= s+ n+" ";
if(rand>n) {
System.out.println("Your guess of "+n+" is too low.");
}
else {
System.out.println("Your guess of "+n+" is too high.");
}
if(count<=5) {
System.out.println("enter a number between 1 and 10: ");
n = scan.nextInt();
}
}
if(count<=5) {
System.out.println("Your guess of "+n+" is CORRECT!");
}else {
System.out.println("Better luck next time!");
}
System.out.println("Your guesses were: "+s);
}
}
Output:
enter a number between 1 and 10:
5
Your guess of 5 is too high.
enter a number between 1 and 10:
6
Your guess of 6 is too high.
enter a number between 1 and 10:
7
Your guess of 7 is too high.
enter a number between 1 and 10:
8
Your guess of 8 is too high.
enter a number between 1 and 10:
9
Your guess of 9 is too high.
Better luck next time!
Your guesses were: 5 6 7 8 9
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.