Professional Documents
Culture Documents
JAVA Guessing Game Tutorial: Written By: Azita Azimi Edited By: Abdul Rahman Sherzad OXUS20 1/28/2014
JAVA Guessing Game Tutorial: Written By: Azita Azimi Edited By: Abdul Rahman Sherzad OXUS20 1/28/2014
TABLE OF CONTENTS
Introduction ....................................................... 3
Conclusion ......................................................... 9
2
Guessing
h ttps :// ww w.fa ceb oo k.co m/O xu s20
Game
INTRODUCTION
In this program we are supposed to make a simple guessing game where the user / player
guess the number selected by the computer and the goal is to introduce the power and
usage of random as well as the how to benefit currentTimeMillis() method of the System
class in order to check how much it took the player guessing the number.
PROBLEM STATEMENT
It is worth having idea and knowledge how the guessing game works before jumping to the
code. When the player runs the program the computer will choose a random number
between 1 and 1000 and in the meanwhile the player will be prompted to guess a number
between 1 and 1000 until he / she guesses the correct number; for every guess, the
computer will either print "Your guess is too high", "Your guess is too low" or "your guess is
correct" . Finally at the end of the game, the guessed number will be shown along with the
number of guesses it took to get the correct number. See followings screenshots as demo:
3
Guessing
h ttps :// ww w.fa ceb oo k.co m/O xu s20
Game
PLAN AND ALGORITHM SOLUTION
Before jumping in the code it is worth planning and having a clear understanding of the
steps required building the program. Both plan and code is needed; but plan first and then
code.
Following steps will act as a map and guide-line enabling the programmer to write the code
easily and efficiently:
Generate random numbers between 1 and MAX_NUMBER which has the value of
Ask the computer choosing a number randomly and store it in a variable for later
Ask the player to guess and input a number between 1 and MAX_NUMBER
Check whether the player guess is either correct, too high or too low comparing
Repeat the game until the player guess the correct number
Prompt the player the correct number and the total number of tries and how much
Next page demonstrates the complete source code of the Guessing Game Number and then
we will explain the source code piece by piece …
4
Guessing
h ttps :// ww w.fa ceb oo k.co m/O xu s20
Game
import java.util.Random;
import javax.swing.JOptionPane;
choice = JOptionPane.showConfirmDialog(null,
"Do you want to play again?", "Confirmation",
JOptionPane.YES_NO_OPTION);
} while (choice != JOptionPane.NO_OPTION);
5
Guessing
h ttps :// ww w.fa ceb oo k.co m/O xu s20
Game
CODE BREAK DOWN STEP BY STEP
First and foremost we will start the program by creating a new class named
"GuessingGameNumber.java" including the main method as follow:
}
}
NOTE:
Please notice you will get an error message when you try to use the Random class
complaining that either you create the class or import it from the java class library.
Therefore, you need to import the class using the Jave import statement at the very top of
the program as follow:
import java.util.Random;
Please note that The same case is true while using the classes which are out of the
java.lang.* packages for example the JOptionPane class which resides under the javax.swing
package.
6
Guessing
h ttps :// ww w.fa ceb oo k.co m/O xu s20
Game
OUTER LOOP AND INNER LOOP
do {
do {
OUTER LOOP
When the program ends the Outer Loop is responsible giving option to the player if he / she
still would to continue playing as well as resets the all the options i.e. the initial random
selection, reset the start time and initial counter, etc.
do {
int selected = rand.nextInt(MAX_NUMBER) + 1;
int count = 0;
start = System.currentTimeMillis();
The variable selected store the initial guess of the program by the computer which
is a number between range of 1 and 1000.
The variable count is initialized with values of zero which keeps track of the number
of times it took the user to guess the correct number.
The variable start keeps track the game start time in order to calculates how much
time it took the user to guess the correct number.
Finally the while with condition executes when the player guess the number
correctly and give the player the option of playing again and/or stop the game.
7
Guessing
h ttps :// ww w.fa ceb oo k.co m/O xu s20
Game
INNER LOOP
On the other hand the Inner Loop responsible comparing the player guess against the
computer guess and then provides input option each time the user guess is incorrect.
do {
input = JOptionPane.showInputDialog("Let's play the guessing game.\n"
+ "Guess a number between 1 AND " + MAX_NUMBER);
guessed = Integer.parseInt(input);
count++;
if (guessed > selected) {
JOptionPane.showMessageDialog(null, "You guessed \""
+ guessed + "\". Your guess is high!");
} else if (guessed < selected) {
JOptionPane.showMessageDialog(null, "You guessed \""
+ guessed + "\". Your guess is low!");
} else if (guessed == selected) {
JOptionPane.showMessageDialog(null, "WOW! You guessed \""
+ guessed + "\". Your guess is correct");
}
} while (selected != guessed);
end = System.currentTimeMillis();
duration = end - start;
JOptionPane.showMessageDialog(null, "You guessed correctly. \nThe correct guess
was \"" + selected + "\".\nYou tried " + count + " times, and " + (duration /
1000d) + " seconds.");
As it was mentioned the Inner Loop is responsible to provide entry option to the player
using JOptionPane.showMessageDialog() method. It is worth mentioning everything reads
from the keyboard is String and needs to be converted to int using the Integer.parseIn()
method. Finally compare it against the computer guess as follow:
if (guessed > selected) {} // if player guess is higher than computer guess
if (guessed < selected) {} // if player guess is lower than computer guess
if (guessed == selected) {} // if player guess is equal computer guess
When the guess is correct then the time will be recorded and the start time subtracted to
calculate the amount of time it took the player and finally prompt the user with details.
8
Guessing
h ttps :// ww w.fa ceb oo k.co m/O xu s20
Game
CONCLUSION
You have noticed we have used Random class in this application to generate random
numbers of integers in a specific range. Random class has many other useful
methods where gives the power to generate random floating point numbers, etc.
Using random concept inside the program has much usages in many application
programs and areas for instance Lottery Applications, Random Advertisement,
Random Security Images, Random Questions with Random Options, etc.