using eclipse, write a java program, that plays the the hi lo guessing game with
ID: 3880216 • Letter: U
Question
using eclipse, write a java program, that plays the the hi lo guessing game with numbers. The program should pick a random number between 1 and 100(inclusive), then repeatedly prompt the user to guess the number. On each guess, report to the user the he or she is correct or that the guess is to high or low. Continue accepting guesses until the user is correct or decides to quit. Use a sentinel value to determine whether the user wants to quit. Count the number of guesses and report the value when the user guesses correctly. At the end of each game rather is quitting or guessing correctly, prompt to determine whether the user wants play again. Continue playing games until the user chooses to stop.
Explanation / Answer
import java.io.*;
import java.util.*;
public class A
{
public static void main(String[] args)
{
System.out.println("Welcome to the game.");
System.out.println("Pick a number: ");
int choice=1;
int maxnum=100;//maximum range of guess
do
{
Random rand = new Random();//to generat the random numbers
int number = rand.nextInt(maxnum);
int tries = 0; //total number of guesses to reach the result
Scanner input = new Scanner(System.in);
int guess;
int win = 0;
while (win == 0)
{ //This while loop ends the code with in it repeat until win === 1
System.out.println("Guess a number between 1 and "+ maxnum +" or enter 999 to quit ");
guess = input.nextInt();
tries++; //increment the trials
if (guess == number)
{//here is the end of the program in terms of winning the game
win = 1; //Since the number is correct win == 1 then ending the loop
}
else if(guess < number)
{
System.out.println("Number is to low, tray again");
//when value is less than the random number
}
else if(guess > number)
{
System.out.println("Number is to high, try again");
//when value is high than the random number
}
else
if(guess==999)
{
System.out.println("User is quitting in mid of the game before it ends");
System.exit(0);//to quit the program
}
}
System.out.println("You win!");
System.out.println("It took you "+ tries + " tries.");
System.out.println("Want to play Again ! Enter 1 to play again or 0 to exit ");
Scanner sc=new Scanner(System.in);
choice = sc.nextInt();
}while(choice!=0);
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.