To learn to use do-while loops You should generate a random number between 1 and
ID: 3826863 • 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
PROGRAM
import java.util.Random;
import java.util.Scanner;
public class randoms {
//assigning flag equals one
static int flag=1;
//method for generation of random numbers
public void generaterandom(int num)
{
Scanner no = new Scanner(System.in);
//for generating random numbers
Random t = new Random();
for(int i =0; i<1; i++){
int randomInteger = t.nextInt(10);
//generated random number is compared with the user input value
if(randomInteger==num)
{
System.out.println("random number"+randomInteger);
System.out.println("well done");
System.out.println("Play again:: 0 to stop");
int play = no.nextInt();
//to stop the game,give the value 0,otherwise give any value
if(play!=0)
{
System.out.println("what is your guess");
Scanner in = new Scanner(System.in);
//reading the next value and calling the generate method
int num1 = in.nextInt();
generaterandom(num1);
}
else
{
//for stopping the game,if input value is 0.flag is set to exit from the loop
System.out.println("Thank you for playing");
flag=0;
break;
}
}
else
{ //printing if the random number and generated value are different
System.out.println("Nope");
System.out.println(randomInteger);
}
}
}
//main method
public static void main(String[] args) {
// TODO Auto-generated method stub
randoms r=new randoms();
do
{
System.out.println("what is your guess");
Scanner in = new Scanner(System.in);
int num = in.nextInt();
//calling the method for generating random numbers
r.generaterandom(num);
}while(flag==1);
}
}
OUTPUT
what is your guess
6
Nope
3
what is your guess
3
Nope
7
what is your guess
2
random number2
well done
Play again:: 0 to stop
0
Thank you for playing
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.