SlideShare a Scribd company logo
2
Most read
5
Most read
2014
JAVA Guessing Game
Tutorial

Written By: Azita Azimi
Edited By:
OXUS20
1/28/2014

Abdul Rahman Sherzad
Guessing
h ttps :// ww w.fa ceb oo k.co m/O xu s20

Game

TABLE OF CONTENTS
Introduction ....................................................... 3
Problem statement .................................................. 3
Plan and Algorithm Solution ........................................ 4
Code Break Down Step By Step ....................................... 6
Variables Declaration and Initialization ......................... 6
Outer Loop and Inner Loop ........................................ 7
Outer Loop ...................................................... 7
Inner Loop ...................................................... 8
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:


Create a new class including main() method

 Create a constant MAX_NUMBER = 1000 indicating the highest guessing number


Generate random numbers between 1 and MAX_NUMBER which has the value of
1000 in our current case and scenario



Ask the computer choosing a number randomly and store it in a variable for later
use and comparison against the player guess.



Ask the player to guess and input a number between 1 and MAX_NUMBER



Keep track of number of guesses the player played and input



Check whether the player guess is either correct, too high or too low comparing
with the initial random selected number



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
time it took the player

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;
public class GuessingGameNumber {
public static void main(String[] args) {
// declare and initialize the required variables
final int MAX_NUMBER = 1000;
Random rand = new Random();
int guessed = 0;
int choice = 1;
String input = "";
// these calculate and display the execution time
long start, end, duration;
// outer loop ask whether you want to continue the game(YES/NO)
do {
int selected = rand.nextInt(MAX_NUMBER) + 1;
int count = 0;
start = System.currentTimeMillis();
// inner loop prompt you if your guess is high, low or correct
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.");
choice = JOptionPane.showConfirmDialog(null,
"Do you want to play again?", "Confirmation",
JOptionPane.YES_NO_OPTION);
} while (choice != JOptionPane.NO_OPTION);
JOptionPane.showMessageDialog(null, "Thanks for playing");
}
}

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:
public class GuessingGameNumber {
public static void main(String[] args) {
}
}

VARIABLES DECLARATION AND INITIALIZATION
Next step is to declare the required variables and initialize them to their default value in
case it is needed as follow:
// declare and initialize the required variables
final int MAX_NUMBER = 1000;
Random rand = new Random();
int guessed = 0;
int choice = 1;
String input = "";
// these calculate and display the execution time
long start, end, duration;

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 {
} while (selected != guessed);
} while (choice != JOptionPane.NO_OPTION);

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();
// inner loop prompt you if your guess is high, low or correct
} while (choice != JOptionPane.NO_OPTION);






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.

// Outer Loop Begin
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.");
choice = JOptionPane.showConfirmDialog(null,
"Confirmation", JOptionPane.YES_NO_OPTION);

"Do

you

want

to

play

again?",

// Outer Loop End

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.
In addition, we have used currentTimeMillis() method in this application to calculate
how much time it took the player to guess the correct guessed number. This method
is so usable in many other environments and cases such as optimization and
measurement of algorithm, killing the execution process if the execution process
took longer abnormal time, etc.

9

More Related Content

PPTX
How to make a presentation effective
Seerat Saleem Rao
 
PPTX
Crm ppt
nileshsen
 
PPTX
ppt of crm
Mundirika Sah
 
PPTX
Informal Communication-Grapevine
Sardar Patel Education Campus, Gujarat, India
 
PDF
5_Lime Soda Process.pdf
SomeshThakur13
 
PPT
Beer lambert Law
Jaleelkabdul Jaleel
 
PPTX
ATM project presentation
Abdul Rafay
 
PPT
Ernest Rutherford
mae2388
 
How to make a presentation effective
Seerat Saleem Rao
 
Crm ppt
nileshsen
 
ppt of crm
Mundirika Sah
 
Informal Communication-Grapevine
Sardar Patel Education Campus, Gujarat, India
 
5_Lime Soda Process.pdf
SomeshThakur13
 
Beer lambert Law
Jaleelkabdul Jaleel
 
ATM project presentation
Abdul Rafay
 
Ernest Rutherford
mae2388
 

What's hot (20)

PPTX
Transport layer
reshmadayma
 
PPTX
Raster scan systems with video controller and display processor
hemanth kumar
 
PPTX
Knowledge representation and Predicate logic
Amey Kerkar
 
DOCX
PAGIN AND SEGMENTATION.docx
ImranBhatti58
 
PPT
Fields of digital image processing slides
Srinath Dhayalamoorthy
 
PPTX
Single pass assembler
Bansari Shah
 
PPTX
weak slot and filler structure
Amey Kerkar
 
PPTX
Video display device
missagrata
 
PPTX
Hidden surface removal
Punyajoy Saha
 
PPTX
Three Address code
Pooja Dixit
 
PPT
Addition and subtraction with signed magnitude data (mano
cs19club
 
PPT
Hardware implementation for Addition and subtraction in Digital Hardware
christyvincent5
 
PPTX
Hangman game is interesting
Muhammad Umer Lari
 
PPTX
Ripple Carry Adder
Aravindreddy Mokireddy
 
PDF
I. AO* SEARCH ALGORITHM
vikas dhakane
 
PPTX
Types of Parser
SomnathMore3
 
PPTX
Check sum
Pooja Jaiswal
 
PPTX
Code optimization
veena venugopal
 
PPTX
Principle source of optimazation
Siva Sathya
 
PDF
Introduction to OpenMP
Akhila Prabhakaran
 
Transport layer
reshmadayma
 
Raster scan systems with video controller and display processor
hemanth kumar
 
Knowledge representation and Predicate logic
Amey Kerkar
 
PAGIN AND SEGMENTATION.docx
ImranBhatti58
 
Fields of digital image processing slides
Srinath Dhayalamoorthy
 
Single pass assembler
Bansari Shah
 
weak slot and filler structure
Amey Kerkar
 
Video display device
missagrata
 
Hidden surface removal
Punyajoy Saha
 
Three Address code
Pooja Dixit
 
Addition and subtraction with signed magnitude data (mano
cs19club
 
Hardware implementation for Addition and subtraction in Digital Hardware
christyvincent5
 
Hangman game is interesting
Muhammad Umer Lari
 
Ripple Carry Adder
Aravindreddy Mokireddy
 
I. AO* SEARCH ALGORITHM
vikas dhakane
 
Types of Parser
SomnathMore3
 
Check sum
Pooja Jaiswal
 
Code optimization
veena venugopal
 
Principle source of optimazation
Siva Sathya
 
Introduction to OpenMP
Akhila Prabhakaran
 
Ad

Viewers also liked (20)

PDF
Java Virtual Keyboard Using Robot, Toolkit and JToggleButton Classes
OXUS 20
 
PDF
PHP Basic and Fundamental Questions and Answers with Detail Explanation
OXUS 20
 
PPTX
Conditional Statement
OXUS 20
 
PDF
Java Regular Expression PART II
OXUS 20
 
PDF
Everything about Object Oriented Programming
Abdul Rahman Sherzad
 
PPTX
TKP Java Notes for Teaching Kids Programming
Lynn Langit
 
PDF
Java Applet and Graphics
OXUS 20
 
PDF
Fal-e-Hafez (Omens of Hafez) Cards in Persian using Java
OXUS 20
 
PDF
Java Unicode with Cool GUI Examples
OXUS 20
 
PDF
Java Regular Expression PART I
OXUS 20
 
PDF
Object Oriented Concept Static vs. Non Static
OXUS 20
 
PPTX
Structure programming – Java Programming – Theory
OXUS 20
 
PDF
Create Splash Screen with Java Step by Step
OXUS 20
 
PDF
Web Design and Development Life Cycle and Technologies
OXUS 20
 
PDF
Everything about Database JOINS and Relationships
OXUS 20
 
PDF
Note - Java Remote Debug
boyw165
 
DOCX
Core java notes with examples
bindur87
 
PDF
Java Unicode with Live GUI Examples
Abdul Rahman Sherzad
 
PDF
Java Virtual Keyboard Using Robot, Toolkit and JToggleButton Classes
Abdul Rahman Sherzad
 
PDF
Jdbc Complete Notes by Java Training Center (Som Sir)
Som Prakash Rai
 
Java Virtual Keyboard Using Robot, Toolkit and JToggleButton Classes
OXUS 20
 
PHP Basic and Fundamental Questions and Answers with Detail Explanation
OXUS 20
 
Conditional Statement
OXUS 20
 
Java Regular Expression PART II
OXUS 20
 
Everything about Object Oriented Programming
Abdul Rahman Sherzad
 
TKP Java Notes for Teaching Kids Programming
Lynn Langit
 
Java Applet and Graphics
OXUS 20
 
Fal-e-Hafez (Omens of Hafez) Cards in Persian using Java
OXUS 20
 
Java Unicode with Cool GUI Examples
OXUS 20
 
Java Regular Expression PART I
OXUS 20
 
Object Oriented Concept Static vs. Non Static
OXUS 20
 
Structure programming – Java Programming – Theory
OXUS 20
 
Create Splash Screen with Java Step by Step
OXUS 20
 
Web Design and Development Life Cycle and Technologies
OXUS 20
 
Everything about Database JOINS and Relationships
OXUS 20
 
Note - Java Remote Debug
boyw165
 
Core java notes with examples
bindur87
 
Java Unicode with Live GUI Examples
Abdul Rahman Sherzad
 
Java Virtual Keyboard Using Robot, Toolkit and JToggleButton Classes
Abdul Rahman Sherzad
 
Jdbc Complete Notes by Java Training Center (Som Sir)
Som Prakash Rai
 
Ad

Similar to Java Guessing Game Number Tutorial (20)

DOCX
Practice
Daman Toor
 
PPTX
Exploring Control Flow: Harnessing While Loops in Python
Programming Homework Help
 
PPT
Ch5(loops)
Uğurcan Uzer
 
PPTX
Computer Science Homework Help
Programming Homework Help
 
PPTX
Python Homework Help
Python Homework Help
 
PDF
Little book of programming challenges
ysolanki78
 
PPT
Python in details
Khalid AL-Dhanhani
 
PPTX
Number Guessing Game using Artiifcal intelligence
afsheenfaiq2
 
PDF
You will write a multi-interface version of the well-known concentra.pdf
FashionColZone
 
PPTX
Repetition Structure.pptx
rhiene05
 
PPTX
Most asked JAVA Interview Questions & Answers.
Questpond
 
DOCX
OverviewThis hands-on lab allows you to follow and experiment w.docx
gerardkortney
 
PPTX
Basic computer-programming-2
lemonmichelangelo
 
DOCX
Ip project
Anurag Surya
 
PPT
09-ch04-1-scanner class in java with explainiation
ShahidSultan24
 
PPTX
JavaScript 101
Mindy McAdams
 
DOCX
PROVIDE COMMENTS TO FELLOW STUDENTS ANSWERS AND PLEASE DON’T SAY G.docx
amrit47
 
PDF
Cc code cards
ysolanki78
 
PPT
ch05-program-logic-indefinite-loops.ppt
Mahyuddin8
 
PPTX
05A_Java_in yemen adenProgramming_IT.pptx
akrmalslami88
 
Practice
Daman Toor
 
Exploring Control Flow: Harnessing While Loops in Python
Programming Homework Help
 
Ch5(loops)
Uğurcan Uzer
 
Computer Science Homework Help
Programming Homework Help
 
Python Homework Help
Python Homework Help
 
Little book of programming challenges
ysolanki78
 
Python in details
Khalid AL-Dhanhani
 
Number Guessing Game using Artiifcal intelligence
afsheenfaiq2
 
You will write a multi-interface version of the well-known concentra.pdf
FashionColZone
 
Repetition Structure.pptx
rhiene05
 
Most asked JAVA Interview Questions & Answers.
Questpond
 
OverviewThis hands-on lab allows you to follow and experiment w.docx
gerardkortney
 
Basic computer-programming-2
lemonmichelangelo
 
Ip project
Anurag Surya
 
09-ch04-1-scanner class in java with explainiation
ShahidSultan24
 
JavaScript 101
Mindy McAdams
 
PROVIDE COMMENTS TO FELLOW STUDENTS ANSWERS AND PLEASE DON’T SAY G.docx
amrit47
 
Cc code cards
ysolanki78
 
ch05-program-logic-indefinite-loops.ppt
Mahyuddin8
 
05A_Java_in yemen adenProgramming_IT.pptx
akrmalslami88
 

More from OXUS 20 (8)

PDF
Java Arrays
OXUS 20
 
PPTX
Java Methods
OXUS 20
 
PDF
Fundamentals of Database Systems Questions and Answers
OXUS 20
 
PDF
JAVA GUI PART III
OXUS 20
 
PDF
Java GUI PART II
OXUS 20
 
PDF
JAVA GUI PART I
OXUS 20
 
PDF
JAVA Programming Questions and Answers PART III
OXUS 20
 
PDF
Object Oriented Programming with Real World Examples
OXUS 20
 
Java Arrays
OXUS 20
 
Java Methods
OXUS 20
 
Fundamentals of Database Systems Questions and Answers
OXUS 20
 
JAVA GUI PART III
OXUS 20
 
Java GUI PART II
OXUS 20
 
JAVA GUI PART I
OXUS 20
 
JAVA Programming Questions and Answers PART III
OXUS 20
 
Object Oriented Programming with Real World Examples
OXUS 20
 

Recently uploaded (20)

PPTX
PPTs-The Rise of Empiresghhhhhhhh (1).pptx
academysrusti114
 
PPTX
Skill Development Program For Physiotherapy Students by SRY.pptx
Prof.Dr.Y.SHANTHOSHRAJA MPT Orthopedic., MSc Microbiology
 
PPTX
TEF & EA Bsc Nursing 5th sem.....BBBpptx
AneetaSharma15
 
PPTX
Dakar Framework Education For All- 2000(Act)
santoshmohalik1
 
PPTX
IMMUNIZATION PROGRAMME pptx
AneetaSharma15
 
PDF
Phylum Arthropoda: Characteristics and Classification, Entomology Lecture
Miraj Khan
 
PDF
2.Reshaping-Indias-Political-Map.ppt/pdf/8th class social science Exploring S...
Sandeep Swamy
 
PPTX
Odoo 18 Sales_ Managing Quotation Validity
Celine George
 
PDF
Sunset Boulevard Student Revision Booklet
jpinnuck
 
PDF
Types of Literary Text: Poetry and Prose
kaelandreabibit
 
PDF
UTS Health Student Promotional Representative_Position Description.pdf
Faculty of Health, University of Technology Sydney
 
PPTX
Measures_of_location_-_Averages_and__percentiles_by_DR SURYA K.pptx
Surya Ganesh
 
PPTX
Tips Management in Odoo 18 POS - Odoo Slides
Celine George
 
PPTX
An introduction to Prepositions for beginners.pptx
drsiddhantnagine
 
PPTX
Care of patients with elImination deviation.pptx
AneetaSharma15
 
PDF
3.The-Rise-of-the-Marathas.pdfppt/pdf/8th class social science Exploring Soci...
Sandeep Swamy
 
PPTX
How to Manage Global Discount in Odoo 18 POS
Celine George
 
PDF
Review of Related Literature & Studies.pdf
Thelma Villaflores
 
PPTX
HISTORY COLLECTION FOR PSYCHIATRIC PATIENTS.pptx
PoojaSen20
 
PPTX
Strengthening open access through collaboration: building connections with OP...
Jisc
 
PPTs-The Rise of Empiresghhhhhhhh (1).pptx
academysrusti114
 
Skill Development Program For Physiotherapy Students by SRY.pptx
Prof.Dr.Y.SHANTHOSHRAJA MPT Orthopedic., MSc Microbiology
 
TEF & EA Bsc Nursing 5th sem.....BBBpptx
AneetaSharma15
 
Dakar Framework Education For All- 2000(Act)
santoshmohalik1
 
IMMUNIZATION PROGRAMME pptx
AneetaSharma15
 
Phylum Arthropoda: Characteristics and Classification, Entomology Lecture
Miraj Khan
 
2.Reshaping-Indias-Political-Map.ppt/pdf/8th class social science Exploring S...
Sandeep Swamy
 
Odoo 18 Sales_ Managing Quotation Validity
Celine George
 
Sunset Boulevard Student Revision Booklet
jpinnuck
 
Types of Literary Text: Poetry and Prose
kaelandreabibit
 
UTS Health Student Promotional Representative_Position Description.pdf
Faculty of Health, University of Technology Sydney
 
Measures_of_location_-_Averages_and__percentiles_by_DR SURYA K.pptx
Surya Ganesh
 
Tips Management in Odoo 18 POS - Odoo Slides
Celine George
 
An introduction to Prepositions for beginners.pptx
drsiddhantnagine
 
Care of patients with elImination deviation.pptx
AneetaSharma15
 
3.The-Rise-of-the-Marathas.pdfppt/pdf/8th class social science Exploring Soci...
Sandeep Swamy
 
How to Manage Global Discount in Odoo 18 POS
Celine George
 
Review of Related Literature & Studies.pdf
Thelma Villaflores
 
HISTORY COLLECTION FOR PSYCHIATRIC PATIENTS.pptx
PoojaSen20
 
Strengthening open access through collaboration: building connections with OP...
Jisc
 

Java Guessing Game Number Tutorial

  • 1. 2014 JAVA Guessing Game Tutorial Written By: Azita Azimi Edited By: OXUS20 1/28/2014 Abdul Rahman Sherzad
  • 2. Guessing h ttps :// ww w.fa ceb oo k.co m/O xu s20 Game TABLE OF CONTENTS Introduction ....................................................... 3 Problem statement .................................................. 3 Plan and Algorithm Solution ........................................ 4 Code Break Down Step By Step ....................................... 6 Variables Declaration and Initialization ......................... 6 Outer Loop and Inner Loop ........................................ 7 Outer Loop ...................................................... 7 Inner Loop ...................................................... 8 Conclusion ......................................................... 9 2
  • 3. 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
  • 4. 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:  Create a new class including main() method  Create a constant MAX_NUMBER = 1000 indicating the highest guessing number  Generate random numbers between 1 and MAX_NUMBER which has the value of 1000 in our current case and scenario  Ask the computer choosing a number randomly and store it in a variable for later use and comparison against the player guess.  Ask the player to guess and input a number between 1 and MAX_NUMBER  Keep track of number of guesses the player played and input  Check whether the player guess is either correct, too high or too low comparing with the initial random selected number  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 time it took the player Next page demonstrates the complete source code of the Guessing Game Number and then we will explain the source code piece by piece … 4
  • 5. Guessing h ttps :// ww w.fa ceb oo k.co m/O xu s20 Game import java.util.Random; import javax.swing.JOptionPane; public class GuessingGameNumber { public static void main(String[] args) { // declare and initialize the required variables final int MAX_NUMBER = 1000; Random rand = new Random(); int guessed = 0; int choice = 1; String input = ""; // these calculate and display the execution time long start, end, duration; // outer loop ask whether you want to continue the game(YES/NO) do { int selected = rand.nextInt(MAX_NUMBER) + 1; int count = 0; start = System.currentTimeMillis(); // inner loop prompt you if your guess is high, low or correct 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."); choice = JOptionPane.showConfirmDialog(null, "Do you want to play again?", "Confirmation", JOptionPane.YES_NO_OPTION); } while (choice != JOptionPane.NO_OPTION); JOptionPane.showMessageDialog(null, "Thanks for playing"); } } 5
  • 6. 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: public class GuessingGameNumber { public static void main(String[] args) { } } VARIABLES DECLARATION AND INITIALIZATION Next step is to declare the required variables and initialize them to their default value in case it is needed as follow: // declare and initialize the required variables final int MAX_NUMBER = 1000; Random rand = new Random(); int guessed = 0; int choice = 1; String input = ""; // these calculate and display the execution time long start, end, duration; 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
  • 7. Guessing h ttps :// ww w.fa ceb oo k.co m/O xu s20 Game OUTER LOOP AND INNER LOOP do { do { } while (selected != guessed); } while (choice != JOptionPane.NO_OPTION); 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(); // inner loop prompt you if your guess is high, low or correct } while (choice != JOptionPane.NO_OPTION);     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
  • 8. 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. // Outer Loop Begin 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."); choice = JOptionPane.showConfirmDialog(null, "Confirmation", JOptionPane.YES_NO_OPTION); "Do you want to play again?", // Outer Loop End 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
  • 9. 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. In addition, we have used currentTimeMillis() method in this application to calculate how much time it took the player to guess the correct guessed number. This method is so usable in many other environments and cases such as optimization and measurement of algorithm, killing the execution process if the execution process took longer abnormal time, etc. 9