In: Computer Science
The goal of this assignment is to give you some experience writing code with control structures in Java.
You will create a number guessing game program. The program will randomly choose a number between 0 and 100 that the user will try to guess. The user will be given a maximum number of tries (10 max) to guess the number. The user wins only when they guess the randomly chosen number before the maximum number of tries expires. Otherwise, the user loses the game. During the course of playing the game, you need to let the user know whether the guess was too high or too low.
The program should display instructions on how to play the game, number of wins, losses, and the total number of guesses.
I want you to use the Java API or other online resources to find
out how to generate a random number.
Hi, Please find my implementation.
Please let me know in case of any issue.
import java.util.InputMismatchException;
import java.util.Random;
import java.util.Scanner;
public class NumberGuess {
public static void main(String[] args) {
Random random = new Random();
Scanner sc = new Scanner(System.in);
int guess;
int looses = 0, wins= 0;
while(true){
System.out.println("Guess a number in range 0-100");
int num = random.nextInt(101); //random number in range 0-100
int i = 1;
while(i <= 10){
try{
System.out.print("Enter your guess: ");
guess = sc.nextInt();
if(guess == num){
System.out.println("You have guessed correctly!!");
wins++;
break;
}else if(guess>num){
System.out.println("Your guess is too high");
}else{
System.out.println("You guess is too low");
}
}catch(InputMismatchException e){
System.out.println("Invalid input. Please enter integer value");
sc.next(); // this consumes the invalid token
}
i++;
}
if( i == 11)
looses++;
// User Input
System.out.println("Do you want to play again(y/n) ? ");
char op = sc.next().charAt(0);
if(op != 'y' && op != 'Y')
break;
}
System.out.println("Number of games played: "+(wins+looses));
System.out.println("Number of wins: "+wins);
System.out.println("Number of losses: "+looses);
}
}
/*
Sample run:
Guess a number in range 0-100
Enter your guess: 45
You guess is too low
Enter your guess: 60
You guess is too low
Enter your guess: 70
Your guess is too high
Enter your guess: 65
You guess is too low
Enter your guess: 67
You guess is too low
Enter your guess: 68
You guess is too low
Enter your guess: 69
You have guessed correctly!!
Do you want to play again(y/n) ?
n
Number of games played: 1
Number of wins: 1
Number of losses: 0
*/