Java Programming Guessing Game program Write a program that
Java Programming:::
Guessing Game program
Write a program that will randomly generate a number (1-10)
Prompt the user to guess the number. The user has 5 tries to guess the correct answer. After the user has either guessed correctly or exceeded the maximum number of tries, prompt the user to Play Again (Y or N). The program will keep a count of how many numbers were guessed correctly and how many numbers the user couldn\'t guess correctly (HINT: the game is played 5 times....Correctly guessed 2 times....Incorrectly guessed 3 times). When you user selects N (doesn\'t want to play anymore) display the counts.
REQUIREMENTS:
1. Use loops, ifs, switch
2. Use methods
3. Error check every entry made
Solution
/**
* The java program NumberGuess that prompts user to guess
* a number in a range of 1 to 10. The program continues until
* guess the number or number of tries is 5.
* */
//NumberGuess.java
import java.util.Random;
import java.util.Scanner;
public class NumberGuess {
public static void main(String[] args) {
Scanner scanner=new Scanner(System.in);
Random rand=null;
int guess;
int userGuess;
int correct=0;
int incorrect=0;
int numGuesses=0;
boolean win=false;
final int GUESS_LIMIT=5;
String choice=\"Y\";
do
{
System.out.println(\"***Welcome to Number guessing game***\");
rand=new Random();
guess=rand.nextInt(10)+1;
while(numGuesses<GUESS_LIMIT && !win)
{
System.out.println(\"Guess a number between 1 and 10 :\");
userGuess=Integer.parseInt(scanner.nextLine());
numGuesses++;
//check if userguess is random number guess
if(userGuess==guess)
{
correct++;
win=true;
break;
}
else if(userGuess<guess)
{
incorrect++;
System.out.println(\"Your guess is too low\");
}
else if(userGuess>guess)
{
incorrect++;
System.out.println(\"Your guess is too high\");
}
}
//prompt to continue the game
System.out.println(\"Do you want to Play Again (Y or N).\");
choice=scanner.nextLine();
}while(!choice.equals(\"N\"));
//Checking if user win
if(win)
System.out.println(\"you correct\");
else
System.out.println(\"Better luck next time!\");
System.out.println(\"The game is played \"+numGuesses
+\" times....Correctly guessed \"+correct+\" times....Incorrectly guessed \"+incorrect+\" times\");
}
}
Output:
***Welcome to Number guessing game***
Guess a number between 1 and 10 :
1
5
Your guess is too high
Guess a number between 1 and 10 :
1
2
Your guess is too high
Guess a number between 1 and 10 :
1
1
Do you want to Play Again (Y or N).
N
you correct
The game is played 3 times....Correctly guessed 1 times....Incorrectly guessed 2 times

