To learn to use do-while loops You should generate a random number between 1 and
ID: 3826841 • Letter: T
Question
To learn to use do-while loops You should generate a random number between 1 and 10, then prompt the user for a guess. If the guess is incorrect then you should print "Nope"; if the guess is correct you should print "Well done". Once the user has guess correctly you should ask them to type 0 to stop the game or any other number to play again. Get the program to generate and output the random number first. Then get the program to play the game just once. Finally get the game to repeat. You will need to use "nested loops" to complete this assignment. What's your guess? 6 Nope. What's your guess? 7 Well done! Play again? (0 to stop): 1 What's your guess? 7 Well done! Play again? (0 to stop): 0 Thanks for playing.Explanation / Answer
GuessingGame.java
import java.util.Random;
import java.util.Scanner;
public class GuessingGame {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
Random r = new Random();
int choice=1;
do{
int randNum = r.nextInt(10)+1;
int guess;
do{
System.out.print("What's your guess? ");
guess = scan.nextInt();
if(guess != 0){
if(guess == randNum){
System.out.println("Well done!");
}
else{
System.out.println("Nope.");
}
}
else{
break;
}
}while(guess != randNum);
System.out.print("Play again? (0 to stop): ");
choice = scan.nextInt();
}while(choice != 0);
System.out.println("Thanks for playing.");
}
}
Output:
What's your guess? 5
Nope.
What's your guess? 4
Nope.
What's your guess? 3
Nope.
What's your guess? 2
Nope.
What's your guess? 1
Nope.
What's your guess? 8
Nope.
What's your guess? 7
Nope.
What's your guess? 9
Nope.
What's your guess? 10
Well done!
Play again? (0 to stop): 1
What's your guess? 10
Nope.
What's your guess? 1
Nope.
What's your guess? 2
Nope.
What's your guess? 3
Nope.
What's your guess? 4
Well done!
Play again? (0 to stop): 0
Thanks for playing.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.