We looked at the following sample program (Guessing.java) before: //************
ID: 3537048 • Letter: W
Question
We looked at the following sample program (Guessing.java) before:
//********************************************************************
// Guessing.java
// Demonstrates the use of a block statement in an if-else.
//********************************************************************
import java.util.*;
public class Guessing
{
//-----------------------------------------------------------------
// Plays a simple guessing game with the user.
//-----------------------------------------------------------------
public static void main (String[ ] args)
{
final int MAX = 10;
int answer, guess;
Scanner scan = new Scanner (System.in);
Random generator = new Random();
answer = generator.nextInt(MAX) + 1;
System.out.print ("I'm thinking of a number between 1 and "
+ MAX + ". Guess what it is: ");
guess = scan.nextInt();
if (guess == answer)
System.out.println ("You got it! Good guessing!");
else
{
System.out.println ("That is not correct, sorry.");
System.out.println ("The number was " + answer);
}
}
The problem of this Guessing program is that it can only allow the user to guess the number once. Now we can do something and modify the program as specified below:
%uF0B7 Change the constant MAX to 200.
%uF0B7 Add a do-while loop to allow the user to keep guessing until the user guesses the right number. To assist the user for the next guess if the current guess is incorrect, your program should print out a message like %u201DHigher!%u201D or %u201CLower!%u201D to let the user know the next guess should go higher or lower. When the user guesses it right, a message like %u201CYou got the right number (168) in x attempts!%u201D where 168 is the number (answer) to be guessed and x is the count of attempts for guessing the number successfully.
Explanation / Answer
// Guessing.java
// Demonstrates the use of a block statement in an if-else.
//********************************************************************
import java.util.*;
public class Guessing
{
//-----------------------------------------------------------------
// Plays a simple guessing game with the user.
//-----------------------------------------------------------------
public static void main (String[ ] args)
{
final int MAX = 200;
int answer, guess;
boolean bool=False;
int i=0;
Scanner scan = new Scanner (System.in);
Random generator = new Random();
answer = generator.nextInt(MAX) + 1;
System.out.print ("I'm thinking of a number between 1 and "
+ MAX + ". Guess what it is: ");
if (guess == answer){
i=i+1;
System.out.println ("You guessed it right in "+i+" trials");
bool=True;}
else if(guess<answer){
System.out.println ("Your guess is lesser");
i=i+1;
}
else{
i=i+1;
System.out.println ("Your guess is greater");
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.