import java.util.Scanner; import java.util.Random; public class Guess { public s
ID: 3810487 • Letter: I
Question
import java.util.Scanner;
import java.util.Random;
public class Guess
{
public static void main(String[] args)
{
int numToGuess; //Number the user tries to guess
int guess; //The user's guess
Random generator = new Random();
//randomly generate the number to guess
//print message asking user to enter a guess
//read in guess
while ( ) //keep going as long as the guess is wrong
{
//print message saying guess is wrong
//get another guess from the user
}
//print message saying guess is right
}
}
File Guess.java(given above) contains the skeleton for a program that uses a while loop to play a guessing game. (This problem is described in the previous lab exercise.) Revise this program so that it uses a do ... while loop rather than a while loop. The general outline using a do... while loop is as follows: ^^^^^^^^^^^^^^^^^^^^^^^
// set up (initializations of the counting variables) ....
do
{
// read in a guess ...
// check the guess and print appropriate messages
...
}
while ( condition );
Explanation / Answer
Guess.java
import java.util.Scanner;
import java.util.Random;
public class Guess
{
public static void main(String[] args)
{
int numToGuess; //Number the user tries to guess
int guess; //The user's guess
Random generator = new Random();
Scanner scan = new Scanner(System.in);
//randomly generate the number to guess
guess = generator.nextInt(10)+1;
//print message asking user to enter a guess
System.out.println("Enter the guess number: ");
//read in guess
numToGuess = scan.nextInt();
do //keep going as long as the guess is wrong
{
//print message saying guess is wrong
if(numToGuess != guess){
System.out.println("Your guess is wrong");
}
System.out.println("Enter the guess number: ");
//read in guess
numToGuess = scan.nextInt();
}while ( numToGuess != guess ) ;
//print message saying guess is right
System.out.println("Your guess is correct");
}
}
Output:
Enter the guess number:
4
Your guess is wrong
Enter the guess number:
5
Your guess is wrong
Enter the guess number:
6
Your guess is wrong
Enter the guess number:
7
Your guess is wrong
Enter the guess number:
8
Your guess is wrong
Enter the guess number:
9
Your guess is wrong
Enter the guess number:
1
Your guess is wrong
Enter the guess number:
2
Your guess is wrong
Enter the guess number:
3
Your guess is correct
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.