Goal: Write a simple number guessing game in java.
The game picks a number between bounds input by the user, then user has to guess the number.
The game will tell you if your guess is too high or too low.
When you guess it, the game will tell you how many guesses it took
Run multiple games and print statistics (# games, # guesses, avg) when all done.
Sample Run:
G U E S S I N G G A M E !
Enter lower and upper bounds:
1
10
Enter a number from 1 to 10 (inclusive):
5
Correct, the number was 5! You got it in 1 tries.
Again? (yes or no):
yes
Enter a number from 1 to 10 (inclusive):
5
Too high...
Enter a number from 1 to 10 (inclusive):
3
Correct, the number was 3! You got it in 2 tries.
Again? (yes or no):
no
You played 2 games and made 3 guesses total (1.5 guesses per game).
T H A N K S F O R P L A Y I N G !
Source Code:
import java.util.Scanner;
import java.util.Random;
class ex{
public static void main(String[] args) {
Scanner scnr=new
Scanner(System.in);
Random rand=new Random();
System.out.println("G U E S S I N G
G A M E ! ");
System.out.println("Enter lower and
upper bounds:");
int min=scnr.nextInt();
int max=scnr.nextInt();
float games=0,guesses=0;
String choice="yes";
while(choice.equals("yes")){
int
userGuess=0;
int
tries=1;
int
rand_int=rand.nextInt((max-min+1))+min;
while(userGuess!=rand_int){
System.out.println("Enter a number from "+min+"
to "+max+" (inclusive):");
userGuess=scnr.nextInt();
++tries;
guesses=guesses+1;
if(userGuess==rand_int){
System.out.println("Correct,the number was "+rand_int+"!you got it
in "+tries+" tries.");
break;
}
else if(userGuess<rand_int)
System.out.println("Too
low...");
else if(userGuess>rand_int)
System.out.println("Too
high...");
}
System.out.println("Again?(yes or no):");
choice=scnr.next();
games=games+1;
}
System.out.println("You played
"+games+" games and made "+guesses+" guesses
total("+(guesses/games)+" guesses for game).");
System.out.println("T H A N K S F O
R P L A Y I N G !");
}
}
Sample input and output:
Get Answers For Free
Most questions answered within 1 hours.