SlideShare a Scribd company logo
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

What's hot

report on snake game
report on snake game report on snake game
report on snake game
azhar niaz
 
Snake game powerpoint presentation by rohit malav
Snake game powerpoint presentation by rohit malavSnake game powerpoint presentation by rohit malav
Snake game powerpoint presentation by rohit malav
Rohit malav
 
Synopsis tic tac toe
Synopsis tic tac toeSynopsis tic tac toe
Synopsis tic tac toe
SYED HOZAIFA ALI
 
Tic tac toe
Tic tac toeTic tac toe
Tic tac toe
Syeda Urooba
 
A Presentation on Development of a Simple Calculator
A Presentation on Development of a Simple CalculatorA Presentation on Development of a Simple Calculator
A Presentation on Development of a Simple CalculatorTheophilus Omoregbee
 
Tic tac toe game with graphics presentation
Tic  tac  toe game with graphics presentationTic  tac  toe game with graphics presentation
Tic tac toe game with graphics presentation
Prionto Abdullah
 
18csl67 vtu lab manual
18csl67 vtu lab manual18csl67 vtu lab manual
18csl67 vtu lab manual
NatsuDragoneel5
 
Game using Java
Game using JavaGame using Java
Final year project presentation
Final year project presentationFinal year project presentation
Final year project presentation
SulemanAliMalik
 
Guess the number
Guess the numberGuess the number
Guess the number
guest9bc737
 
Final project report of a game
Final project report of a gameFinal project report of a game
Final project report of a game
Nadia Nahar
 
Android Application And Unity3D Game Documentation
Android Application And Unity3D Game DocumentationAndroid Application And Unity3D Game Documentation
Android Application And Unity3D Game Documentation
Sneh Raval
 
Ludo game using c++ with documentation
Ludo game using c++ with documentation Ludo game using c++ with documentation
Ludo game using c++ with documentation
Mauryasuraj98
 
Tic Tac Toe
Tic Tac ToeTic Tac Toe
Tic Tac Toe ppt
Tic Tac Toe pptTic Tac Toe ppt
Tic Tac Toe ppt
SanchitRastogi15
 
Game project Final presentation
Game project Final presentationGame project Final presentation
Game project Final presentationgemmalunney
 
Game development life cycle
Game development life cycleGame development life cycle
Game development life cycle
Sarah Alazab
 
Flappy bird game in c#
Flappy bird game in c#Flappy bird game in c#
Flappy bird game in c#
Comstas
 
484478584-Presentation-on-Snake-game-pptx.pptx
484478584-Presentation-on-Snake-game-pptx.pptx484478584-Presentation-on-Snake-game-pptx.pptx
484478584-Presentation-on-Snake-game-pptx.pptx
RohanKshirsagar16
 
Black book
Black bookBlack book
Black book
PawanYadav348
 

What's hot (20)

report on snake game
report on snake game report on snake game
report on snake game
 
Snake game powerpoint presentation by rohit malav
Snake game powerpoint presentation by rohit malavSnake game powerpoint presentation by rohit malav
Snake game powerpoint presentation by rohit malav
 
Synopsis tic tac toe
Synopsis tic tac toeSynopsis tic tac toe
Synopsis tic tac toe
 
Tic tac toe
Tic tac toeTic tac toe
Tic tac toe
 
A Presentation on Development of a Simple Calculator
A Presentation on Development of a Simple CalculatorA Presentation on Development of a Simple Calculator
A Presentation on Development of a Simple Calculator
 
Tic tac toe game with graphics presentation
Tic  tac  toe game with graphics presentationTic  tac  toe game with graphics presentation
Tic tac toe game with graphics presentation
 
18csl67 vtu lab manual
18csl67 vtu lab manual18csl67 vtu lab manual
18csl67 vtu lab manual
 
Game using Java
Game using JavaGame using Java
Game using Java
 
Final year project presentation
Final year project presentationFinal year project presentation
Final year project presentation
 
Guess the number
Guess the numberGuess the number
Guess the number
 
Final project report of a game
Final project report of a gameFinal project report of a game
Final project report of a game
 
Android Application And Unity3D Game Documentation
Android Application And Unity3D Game DocumentationAndroid Application And Unity3D Game Documentation
Android Application And Unity3D Game Documentation
 
Ludo game using c++ with documentation
Ludo game using c++ with documentation Ludo game using c++ with documentation
Ludo game using c++ with documentation
 
Tic Tac Toe
Tic Tac ToeTic Tac Toe
Tic Tac Toe
 
Tic Tac Toe ppt
Tic Tac Toe pptTic Tac Toe ppt
Tic Tac Toe ppt
 
Game project Final presentation
Game project Final presentationGame project Final presentation
Game project Final presentation
 
Game development life cycle
Game development life cycleGame development life cycle
Game development life cycle
 
Flappy bird game in c#
Flappy bird game in c#Flappy bird game in c#
Flappy bird game in c#
 
484478584-Presentation-on-Snake-game-pptx.pptx
484478584-Presentation-on-Snake-game-pptx.pptx484478584-Presentation-on-Snake-game-pptx.pptx
484478584-Presentation-on-Snake-game-pptx.pptx
 
Black book
Black bookBlack book
Black book
 

Viewers also liked

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

Viewers also liked (20)

Java Virtual Keyboard Using Robot, Toolkit and JToggleButton Classes
Java Virtual Keyboard Using Robot, Toolkit and JToggleButton ClassesJava Virtual Keyboard Using Robot, Toolkit and JToggleButton Classes
Java Virtual Keyboard Using Robot, Toolkit and JToggleButton Classes
 
PHP Basic and Fundamental Questions and Answers with Detail Explanation
PHP Basic and Fundamental Questions and Answers with Detail ExplanationPHP Basic and Fundamental Questions and Answers with Detail Explanation
PHP Basic and Fundamental Questions and Answers with Detail Explanation
 
Conditional Statement
Conditional Statement Conditional Statement
Conditional Statement
 
Java Regular Expression PART II
Java Regular Expression PART IIJava Regular Expression PART II
Java Regular Expression PART II
 
Everything about Object Oriented Programming
Everything about Object Oriented ProgrammingEverything about Object Oriented Programming
Everything about Object Oriented Programming
 
TKP Java Notes for Teaching Kids Programming
TKP Java Notes for Teaching Kids ProgrammingTKP Java Notes for Teaching Kids Programming
TKP Java Notes for Teaching Kids Programming
 
Java Applet and Graphics
Java Applet and GraphicsJava Applet and Graphics
Java Applet and Graphics
 
Fal-e-Hafez (Omens of Hafez) Cards in Persian using Java
Fal-e-Hafez (Omens of Hafez) Cards in Persian using JavaFal-e-Hafez (Omens of Hafez) Cards in Persian using Java
Fal-e-Hafez (Omens of Hafez) Cards in Persian using Java
 
Java Unicode with Cool GUI Examples
Java Unicode with Cool GUI ExamplesJava Unicode with Cool GUI Examples
Java Unicode with Cool GUI Examples
 
Java Regular Expression PART I
Java Regular Expression PART IJava Regular Expression PART I
Java Regular Expression PART I
 
Object Oriented Concept Static vs. Non Static
Object Oriented Concept Static vs. Non StaticObject Oriented Concept Static vs. Non Static
Object Oriented Concept Static vs. Non Static
 
Structure programming – Java Programming – Theory
Structure programming – Java Programming – TheoryStructure programming – Java Programming – Theory
Structure programming – Java Programming – Theory
 
Create Splash Screen with Java Step by Step
Create Splash Screen with Java Step by StepCreate Splash Screen with Java Step by Step
Create Splash Screen with Java Step by Step
 
Web Design and Development Life Cycle and Technologies
Web Design and Development Life Cycle and TechnologiesWeb Design and Development Life Cycle and Technologies
Web Design and Development Life Cycle and Technologies
 
Everything about Database JOINS and Relationships
Everything about Database JOINS and RelationshipsEverything about Database JOINS and Relationships
Everything about Database JOINS and Relationships
 
Note - Java Remote Debug
Note - Java Remote DebugNote - Java Remote Debug
Note - Java Remote Debug
 
Core java notes with examples
Core java notes with examplesCore java notes with examples
Core java notes with examples
 
Java Unicode with Live GUI Examples
Java Unicode with Live GUI ExamplesJava Unicode with Live GUI Examples
Java Unicode with Live GUI Examples
 
Java Virtual Keyboard Using Robot, Toolkit and JToggleButton Classes
Java Virtual Keyboard Using Robot, Toolkit and JToggleButton ClassesJava Virtual Keyboard Using Robot, Toolkit and JToggleButton Classes
Java Virtual Keyboard Using Robot, Toolkit and JToggleButton Classes
 
Jdbc Complete Notes by Java Training Center (Som Sir)
Jdbc Complete Notes by Java Training Center (Som Sir)Jdbc Complete Notes by Java Training Center (Som Sir)
Jdbc Complete Notes by Java Training Center (Som Sir)
 

Similar to Java Guessing Game Number Tutorial

Practice
PracticePractice
Practice
Daman Toor
 
Computer Science Homework Help
Computer Science Homework HelpComputer Science Homework Help
Computer Science Homework Help
Programming Homework Help
 
Python Homework Help
Python Homework HelpPython Homework Help
Python Homework Help
Python Homework Help
 
Little book of programming challenges
Little book of programming challengesLittle book of programming challenges
Little book of programming challenges
ysolanki78
 
Python in details
Python in detailsPython in details
Python in details
Khalid AL-Dhanhani
 
You will write a multi-interface version of the well-known concentra.pdf
You will write a multi-interface version of the well-known concentra.pdfYou will write a multi-interface version of the well-known concentra.pdf
You will write a multi-interface version of the well-known concentra.pdf
FashionColZone
 
Repetition Structure.pptx
Repetition Structure.pptxRepetition Structure.pptx
Repetition Structure.pptx
rhiene05
 
Most asked JAVA Interview Questions & Answers.
Most asked JAVA Interview Questions & Answers.Most asked JAVA Interview Questions & Answers.
Most asked JAVA Interview Questions & Answers.
Questpond
 
OverviewThis hands-on lab allows you to follow and experiment w.docx
OverviewThis hands-on lab allows you to follow and experiment w.docxOverviewThis hands-on lab allows you to follow and experiment w.docx
OverviewThis hands-on lab allows you to follow and experiment w.docx
gerardkortney
 
Basic computer-programming-2
Basic computer-programming-2Basic computer-programming-2
Basic computer-programming-2
lemonmichelangelo
 
Ip project
Ip projectIp project
Ip project
Anurag Surya
 
JavaScript 101
JavaScript 101JavaScript 101
JavaScript 101
Mindy McAdams
 
PROVIDE COMMENTS TO FELLOW STUDENTS ANSWERS AND PLEASE DON’T SAY G.docx
PROVIDE COMMENTS TO FELLOW STUDENTS ANSWERS AND PLEASE DON’T SAY G.docxPROVIDE COMMENTS TO FELLOW STUDENTS ANSWERS AND PLEASE DON’T SAY G.docx
PROVIDE COMMENTS TO FELLOW STUDENTS ANSWERS AND PLEASE DON’T SAY G.docx
amrit47
 
Cc code cards
Cc code cardsCc code cards
Cc code cards
ysolanki78
 
ch05-program-logic-indefinite-loops.ppt
ch05-program-logic-indefinite-loops.pptch05-program-logic-indefinite-loops.ppt
ch05-program-logic-indefinite-loops.ppt
Mahyuddin8
 
3.2 looping statement
3.2 looping statement3.2 looping statement
3.2 looping statement
PhD Research Scholar
 
C++ Course - Lesson 1
C++ Course - Lesson 1C++ Course - Lesson 1
C++ Course - Lesson 1
Mohamed Ahmed
 
Java Foundations: Basic Syntax, Conditions, Loops
Java Foundations: Basic Syntax, Conditions, LoopsJava Foundations: Basic Syntax, Conditions, Loops
Java Foundations: Basic Syntax, Conditions, Loops
Svetlin Nakov
 
TrackPad Destroyer
TrackPad DestroyerTrackPad Destroyer
TrackPad Destroyer
PubNub
 

Similar to Java Guessing Game Number Tutorial (20)

Practice
PracticePractice
Practice
 
Ch5(loops)
Ch5(loops)Ch5(loops)
Ch5(loops)
 
Computer Science Homework Help
Computer Science Homework HelpComputer Science Homework Help
Computer Science Homework Help
 
Python Homework Help
Python Homework HelpPython Homework Help
Python Homework Help
 
Little book of programming challenges
Little book of programming challengesLittle book of programming challenges
Little book of programming challenges
 
Python in details
Python in detailsPython in details
Python in details
 
You will write a multi-interface version of the well-known concentra.pdf
You will write a multi-interface version of the well-known concentra.pdfYou will write a multi-interface version of the well-known concentra.pdf
You will write a multi-interface version of the well-known concentra.pdf
 
Repetition Structure.pptx
Repetition Structure.pptxRepetition Structure.pptx
Repetition Structure.pptx
 
Most asked JAVA Interview Questions & Answers.
Most asked JAVA Interview Questions & Answers.Most asked JAVA Interview Questions & Answers.
Most asked JAVA Interview Questions & Answers.
 
OverviewThis hands-on lab allows you to follow and experiment w.docx
OverviewThis hands-on lab allows you to follow and experiment w.docxOverviewThis hands-on lab allows you to follow and experiment w.docx
OverviewThis hands-on lab allows you to follow and experiment w.docx
 
Basic computer-programming-2
Basic computer-programming-2Basic computer-programming-2
Basic computer-programming-2
 
Ip project
Ip projectIp project
Ip project
 
JavaScript 101
JavaScript 101JavaScript 101
JavaScript 101
 
PROVIDE COMMENTS TO FELLOW STUDENTS ANSWERS AND PLEASE DON’T SAY G.docx
PROVIDE COMMENTS TO FELLOW STUDENTS ANSWERS AND PLEASE DON’T SAY G.docxPROVIDE COMMENTS TO FELLOW STUDENTS ANSWERS AND PLEASE DON’T SAY G.docx
PROVIDE COMMENTS TO FELLOW STUDENTS ANSWERS AND PLEASE DON’T SAY G.docx
 
Cc code cards
Cc code cardsCc code cards
Cc code cards
 
ch05-program-logic-indefinite-loops.ppt
ch05-program-logic-indefinite-loops.pptch05-program-logic-indefinite-loops.ppt
ch05-program-logic-indefinite-loops.ppt
 
3.2 looping statement
3.2 looping statement3.2 looping statement
3.2 looping statement
 
C++ Course - Lesson 1
C++ Course - Lesson 1C++ Course - Lesson 1
C++ Course - Lesson 1
 
Java Foundations: Basic Syntax, Conditions, Loops
Java Foundations: Basic Syntax, Conditions, LoopsJava Foundations: Basic Syntax, Conditions, Loops
Java Foundations: Basic Syntax, Conditions, Loops
 
TrackPad Destroyer
TrackPad DestroyerTrackPad Destroyer
TrackPad Destroyer
 

More from OXUS 20

Java Arrays
Java ArraysJava Arrays
Java Arrays
OXUS 20
 
Java Methods
Java MethodsJava Methods
Java MethodsOXUS 20
 
Fundamentals of Database Systems Questions and Answers
Fundamentals of Database Systems Questions and AnswersFundamentals of Database Systems Questions and Answers
Fundamentals of Database Systems Questions and Answers
OXUS 20
 
JAVA GUI PART III
JAVA GUI PART IIIJAVA GUI PART III
JAVA GUI PART III
OXUS 20
 
Java GUI PART II
Java GUI PART IIJava GUI PART II
Java GUI PART II
OXUS 20
 
JAVA GUI PART I
JAVA GUI PART IJAVA GUI PART I
JAVA GUI PART I
OXUS 20
 
JAVA Programming Questions and Answers PART III
JAVA Programming Questions and Answers PART IIIJAVA Programming Questions and Answers PART III
JAVA Programming Questions and Answers PART IIIOXUS 20
 
Object Oriented Programming with Real World Examples
Object Oriented Programming with Real World ExamplesObject Oriented Programming with Real World Examples
Object Oriented Programming with Real World Examples
OXUS 20
 

More from OXUS 20 (8)

Java Arrays
Java ArraysJava Arrays
Java Arrays
 
Java Methods
Java MethodsJava Methods
Java Methods
 
Fundamentals of Database Systems Questions and Answers
Fundamentals of Database Systems Questions and AnswersFundamentals of Database Systems Questions and Answers
Fundamentals of Database Systems Questions and Answers
 
JAVA GUI PART III
JAVA GUI PART IIIJAVA GUI PART III
JAVA GUI PART III
 
Java GUI PART II
Java GUI PART IIJava GUI PART II
Java GUI PART II
 
JAVA GUI PART I
JAVA GUI PART IJAVA GUI PART I
JAVA GUI PART I
 
JAVA Programming Questions and Answers PART III
JAVA Programming Questions and Answers PART IIIJAVA Programming Questions and Answers PART III
JAVA Programming Questions and Answers PART III
 
Object Oriented Programming with Real World Examples
Object Oriented Programming with Real World ExamplesObject Oriented Programming with Real World Examples
Object Oriented Programming with Real World Examples
 

Recently uploaded

DRUGS AND ITS classification slide share
DRUGS AND ITS classification slide shareDRUGS AND ITS classification slide share
DRUGS AND ITS classification slide share
taiba qazi
 
ANATOMY AND BIOMECHANICS OF HIP JOINT.pdf
ANATOMY AND BIOMECHANICS OF HIP JOINT.pdfANATOMY AND BIOMECHANICS OF HIP JOINT.pdf
ANATOMY AND BIOMECHANICS OF HIP JOINT.pdf
Priyankaranawat4
 
Aficamten in HCM (SEQUOIA HCM TRIAL 2024)
Aficamten in HCM (SEQUOIA HCM TRIAL 2024)Aficamten in HCM (SEQUOIA HCM TRIAL 2024)
Aficamten in HCM (SEQUOIA HCM TRIAL 2024)
Ashish Kohli
 
The simplified electron and muon model, Oscillating Spacetime: The Foundation...
The simplified electron and muon model, Oscillating Spacetime: The Foundation...The simplified electron and muon model, Oscillating Spacetime: The Foundation...
The simplified electron and muon model, Oscillating Spacetime: The Foundation...
RitikBhardwaj56
 
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...
Dr. Vinod Kumar Kanvaria
 
MASS MEDIA STUDIES-835-CLASS XI Resource Material.pdf
MASS MEDIA STUDIES-835-CLASS XI Resource Material.pdfMASS MEDIA STUDIES-835-CLASS XI Resource Material.pdf
MASS MEDIA STUDIES-835-CLASS XI Resource Material.pdf
goswamiyash170123
 
A Survey of Techniques for Maximizing LLM Performance.pptx
A Survey of Techniques for Maximizing LLM Performance.pptxA Survey of Techniques for Maximizing LLM Performance.pptx
A Survey of Techniques for Maximizing LLM Performance.pptx
thanhdowork
 
S1-Introduction-Biopesticides in ICM.pptx
S1-Introduction-Biopesticides in ICM.pptxS1-Introduction-Biopesticides in ICM.pptx
S1-Introduction-Biopesticides in ICM.pptx
tarandeep35
 
PCOS corelations and management through Ayurveda.
PCOS corelations and management through Ayurveda.PCOS corelations and management through Ayurveda.
PCOS corelations and management through Ayurveda.
Dr. Shivangi Singh Parihar
 
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdfUnit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Thiyagu K
 
Group Presentation 2 Economics.Ariana Buscigliopptx
Group Presentation 2 Economics.Ariana BuscigliopptxGroup Presentation 2 Economics.Ariana Buscigliopptx
Group Presentation 2 Economics.Ariana Buscigliopptx
ArianaBusciglio
 
Chapter 4 - Islamic Financial Institutions in Malaysia.pptx
Chapter 4 - Islamic Financial Institutions in Malaysia.pptxChapter 4 - Islamic Financial Institutions in Malaysia.pptx
Chapter 4 - Islamic Financial Institutions in Malaysia.pptx
Mohd Adib Abd Muin, Senior Lecturer at Universiti Utara Malaysia
 
PIMS Job Advertisement 2024.pdf Islamabad
PIMS Job Advertisement 2024.pdf IslamabadPIMS Job Advertisement 2024.pdf Islamabad
PIMS Job Advertisement 2024.pdf Islamabad
AyyanKhan40
 
MATATAG CURRICULUM: ASSESSING THE READINESS OF ELEM. PUBLIC SCHOOL TEACHERS I...
MATATAG CURRICULUM: ASSESSING THE READINESS OF ELEM. PUBLIC SCHOOL TEACHERS I...MATATAG CURRICULUM: ASSESSING THE READINESS OF ELEM. PUBLIC SCHOOL TEACHERS I...
MATATAG CURRICULUM: ASSESSING THE READINESS OF ELEM. PUBLIC SCHOOL TEACHERS I...
NelTorrente
 
The Diamonds of 2023-2024 in the IGRA collection
The Diamonds of 2023-2024 in the IGRA collectionThe Diamonds of 2023-2024 in the IGRA collection
The Diamonds of 2023-2024 in the IGRA collection
Israel Genealogy Research Association
 
RPMS TEMPLATE FOR SCHOOL YEAR 2023-2024 FOR TEACHER 1 TO TEACHER 3
RPMS TEMPLATE FOR SCHOOL YEAR 2023-2024 FOR TEACHER 1 TO TEACHER 3RPMS TEMPLATE FOR SCHOOL YEAR 2023-2024 FOR TEACHER 1 TO TEACHER 3
RPMS TEMPLATE FOR SCHOOL YEAR 2023-2024 FOR TEACHER 1 TO TEACHER 3
IreneSebastianRueco1
 
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
Levi Shapiro
 
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
EugeneSaldivar
 
Digital Artifact 2 - Investigating Pavilion Designs
Digital Artifact 2 - Investigating Pavilion DesignsDigital Artifact 2 - Investigating Pavilion Designs
Digital Artifact 2 - Investigating Pavilion Designs
chanes7
 
Advantages and Disadvantages of CMS from an SEO Perspective
Advantages and Disadvantages of CMS from an SEO PerspectiveAdvantages and Disadvantages of CMS from an SEO Perspective
Advantages and Disadvantages of CMS from an SEO Perspective
Krisztián Száraz
 

Recently uploaded (20)

DRUGS AND ITS classification slide share
DRUGS AND ITS classification slide shareDRUGS AND ITS classification slide share
DRUGS AND ITS classification slide share
 
ANATOMY AND BIOMECHANICS OF HIP JOINT.pdf
ANATOMY AND BIOMECHANICS OF HIP JOINT.pdfANATOMY AND BIOMECHANICS OF HIP JOINT.pdf
ANATOMY AND BIOMECHANICS OF HIP JOINT.pdf
 
Aficamten in HCM (SEQUOIA HCM TRIAL 2024)
Aficamten in HCM (SEQUOIA HCM TRIAL 2024)Aficamten in HCM (SEQUOIA HCM TRIAL 2024)
Aficamten in HCM (SEQUOIA HCM TRIAL 2024)
 
The simplified electron and muon model, Oscillating Spacetime: The Foundation...
The simplified electron and muon model, Oscillating Spacetime: The Foundation...The simplified electron and muon model, Oscillating Spacetime: The Foundation...
The simplified electron and muon model, Oscillating Spacetime: The Foundation...
 
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...
 
MASS MEDIA STUDIES-835-CLASS XI Resource Material.pdf
MASS MEDIA STUDIES-835-CLASS XI Resource Material.pdfMASS MEDIA STUDIES-835-CLASS XI Resource Material.pdf
MASS MEDIA STUDIES-835-CLASS XI Resource Material.pdf
 
A Survey of Techniques for Maximizing LLM Performance.pptx
A Survey of Techniques for Maximizing LLM Performance.pptxA Survey of Techniques for Maximizing LLM Performance.pptx
A Survey of Techniques for Maximizing LLM Performance.pptx
 
S1-Introduction-Biopesticides in ICM.pptx
S1-Introduction-Biopesticides in ICM.pptxS1-Introduction-Biopesticides in ICM.pptx
S1-Introduction-Biopesticides in ICM.pptx
 
PCOS corelations and management through Ayurveda.
PCOS corelations and management through Ayurveda.PCOS corelations and management through Ayurveda.
PCOS corelations and management through Ayurveda.
 
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdfUnit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdf
 
Group Presentation 2 Economics.Ariana Buscigliopptx
Group Presentation 2 Economics.Ariana BuscigliopptxGroup Presentation 2 Economics.Ariana Buscigliopptx
Group Presentation 2 Economics.Ariana Buscigliopptx
 
Chapter 4 - Islamic Financial Institutions in Malaysia.pptx
Chapter 4 - Islamic Financial Institutions in Malaysia.pptxChapter 4 - Islamic Financial Institutions in Malaysia.pptx
Chapter 4 - Islamic Financial Institutions in Malaysia.pptx
 
PIMS Job Advertisement 2024.pdf Islamabad
PIMS Job Advertisement 2024.pdf IslamabadPIMS Job Advertisement 2024.pdf Islamabad
PIMS Job Advertisement 2024.pdf Islamabad
 
MATATAG CURRICULUM: ASSESSING THE READINESS OF ELEM. PUBLIC SCHOOL TEACHERS I...
MATATAG CURRICULUM: ASSESSING THE READINESS OF ELEM. PUBLIC SCHOOL TEACHERS I...MATATAG CURRICULUM: ASSESSING THE READINESS OF ELEM. PUBLIC SCHOOL TEACHERS I...
MATATAG CURRICULUM: ASSESSING THE READINESS OF ELEM. PUBLIC SCHOOL TEACHERS I...
 
The Diamonds of 2023-2024 in the IGRA collection
The Diamonds of 2023-2024 in the IGRA collectionThe Diamonds of 2023-2024 in the IGRA collection
The Diamonds of 2023-2024 in the IGRA collection
 
RPMS TEMPLATE FOR SCHOOL YEAR 2023-2024 FOR TEACHER 1 TO TEACHER 3
RPMS TEMPLATE FOR SCHOOL YEAR 2023-2024 FOR TEACHER 1 TO TEACHER 3RPMS TEMPLATE FOR SCHOOL YEAR 2023-2024 FOR TEACHER 1 TO TEACHER 3
RPMS TEMPLATE FOR SCHOOL YEAR 2023-2024 FOR TEACHER 1 TO TEACHER 3
 
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
 
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
 
Digital Artifact 2 - Investigating Pavilion Designs
Digital Artifact 2 - Investigating Pavilion DesignsDigital Artifact 2 - Investigating Pavilion Designs
Digital Artifact 2 - Investigating Pavilion Designs
 
Advantages and Disadvantages of CMS from an SEO Perspective
Advantages and Disadvantages of CMS from an SEO PerspectiveAdvantages and Disadvantages of CMS from an SEO Perspective
Advantages and Disadvantages of CMS from an SEO Perspective
 

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