SlideShare a Scribd company logo
1 of 19
Practice. Developing "number guessing
game" step by step
In the lesson we will practise using the basic Java tools learned in previous articles. To do it let's
develop the "Guess game". Its rules are as follows:
 Computer proposes a number from 1 to 1000.
 Human player tries to guess it. One enters a guess and computer tells if the number
matches or it is smaller/greater than the proposed one.
 Game continues, until player guesses the number.
Step 1. Class & main function
Let's call the class "NumberGuessingGame" and add empty main function. It's completely valid
program you can compile and run, but it doesn't print anything to the console yet.
public class NumberGuessingGame {
public static void main(String[] args) {
}
}
Step 2. Secret number
To propose a secret number, we declare a variable secretNumber of type int and use
Math.random() function to give it random value in range 1..1000.
public class NumberGuessingGame {
public static void main(String[] args) {
int secretNumber;
secretNumber = (int) (Math.random() * 999 + 1);
System.out.println("Secret number is " + secretNumber); // to be
removed later
}
}
Secret number is 230
Don't worry, if you don't understand how things with random work. It's not a subject of the
lesson, so just believe it. Note, that program exposes secret number to player at the moment, but
we will remove the line printing the proposal in the final version.
Step 3. Asking user for a guess
In order to get input from user, we declare another variable guess of type int. Code, reading
input from user is not to be discussed in detail here, so take it on trust.
import java.util.Scanner;
public class NumberGuessingGame {
public static void main(String[] args) {
int secretNumber;
secretNumber = (int) (Math.random() * 999 + 1);
System.out.println("Secret number is " + secretNumber); // to be
removed
// later
Scanner keyboard = new Scanner(System.in);
int guess;
System.out.print("Enter a guess: ");
guess = keyboard.nextInt();
System.out.println("Your guess is " + guess);
}
}
Secret number is 78
Enter a guess: 555
Your guess is 555
Step 4. Checking if guess is right
Now let's check if human player's guess is right. If so program should print corresponding
message. Otherwise, tell user that a guess is smaller/greater than the proposed number. To test
the program let's try all three cases (remember that we peeked the secret number).
import java.util.Scanner;
public class NumberGuessingGame {
public static void main(String[] args) {
int secretNumber;
secretNumber = (int) (Math.random() * 999 + 1);
System.out.println("Secret number is " + secretNumber); // to be
removed
// later
Scanner keyboard = new Scanner(System.in);
int guess;
System.out.print("Enter a guess: ");
guess = keyboard.nextInt();
System.out.println("Your guess is " + guess);
if (guess == secretNumber)
System.out.println("Your guess is correct.
Congratulations!");
else if (guess < secretNumber)
System.out
.println("Your guess is smaller than the secret
number.");
else if (guess > secretNumber)
System.out
.println("Your guess is greater than the secret
number.");
}
}
Secret number is 938
Enter a guess: 938
Your guess is 938
Your guess is correct. Congratulations!
Secret number is 478
Enter a guess: 222
Your guess is 222
Your guess is smaller than the secret number.
Secret number is 559
Enter a guess: 777
Your guess is 777
Your guess is greater than the secret number.
Things seem to be working ok.
Step 5. Add tries
At the moment user has only one attempt to guess a number, which is, obvious, not sufficient.
Our next step is about giving user as many attempts as one needs. For this purpose let's use do-
while loop, because user must enter a guess at least once.
import java.util.Scanner;
public class NumberGuessingGame {
public static void main(String[] args) {
int secretNumber;
secretNumber = (int) (Math.random() * 999 + 1);
System.out.println("Secret number is " + secretNumber); // to be
removed
// later
Scanner keyboard = new Scanner(System.in);
int guess;
do {
System.out.print("Enter a guess: ");
guess = keyboard.nextInt();
System.out.println("Your guess is " + guess);
if (guess == secretNumber)
System.out.println("Your guess is correct.
Congratulations!");
else if (guess < secretNumber)
System.out
.println("Your guess is smaller than the
secret number.");
else if (guess > secretNumber)
System.out
.println("Your guess is greater than the
secret number.");
} while (guess != secretNumber);
}
}
Secret number is 504
Enter a guess: 777
Your guess is 777
Your guess is greater than the secret number.
Enter a guess: 333
Your guess is 333
Your guess is smaller than the secret number.
Enter a guess: 504
Your guess is 504
Your guess is correct. Congratulations!
Final step. Make it glow
Just before we consider the program to be complete, let's remove the code, used for debug
purposes.
import java.util.Scanner;
public class NumberGuessingGame {
public static void main(String[] args) {
int secretNumber;
secretNumber = (int) (Math.random() * 999 + 1);
Scanner keyboard = new Scanner(System.in);
int guess;
do {
System.out.print("Enter a guess (1-1000): ");
guess = keyboard.nextInt();
if (guess == secretNumber)
System.out.println("Your guess is correct.
Congratulations!");
else if (guess < secretNumber)
System.out
.println("Your guess is smaller than the
secret number.");
else if (guess > secretNumber)
System.out
.println("Your guess is greater than the
secret number.");
} while (guess != secretNumber);
}
}
Enter a guess (1-1000): 500
Your guess is greater than the secret number.
Enter a guess (1-1000): 250
Your guess is smaller than the secret number.
Enter a guess (1-1000): 375
Your guess is smaller than the secret number.
Enter a guess (1-1000): 437
Your guess is smaller than the secret number.
Enter a guess (1-1000): 468
Your guess is smaller than the secret number.
Enter a guess (1-1000): 484
Your guess is greater than the secret number.
Enter a guess (1-1000): 476
Your guess is greater than the secret number.
Enter a guess (1-1000): 472
Your guess is correct. Congratulations!
Extra tasks
If you would like to practise on your own, there are suggestions of possible improvements:
1. Check, if user enters the number in range 1.1000 and force one to re-enter a guess in case
it is out of bounds.
2. Limit the number of attempts.
3. Add more than one round and wins/loses score.
In current practice lesson we are going to develop a menu-driven application to manage simple
bank account. It supports following operations:
 deposit money;
 withdraw money;
 check balance.
Application is driven by a text menu.
Skeleton
First of all, let's create an application to run infinitely and ask user for a choice, until quit option
is chosen:
import java.util.Scanner;
public class BankAccount {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int userChoice;
boolean quit = false;
do {
System.out.print("Your choice, 0 to quit: ");
userChoice = in.nextInt();
if (userChoice == 0)
quit = true;
} while (!quit);
}
}
Your choice, 0 to quit: 2
Your choice, 0 to quit: 6
Your choice, 0 to quit: 0
Bye!
Draw your attention to boolean variable quit, which is responsible for correct loop interruption.
What a reason to declare additional variable, if one can check exit condition right in while
statement? It's the matter of good programming style. Later you'll see why.
Menu
Now let's add a menu and empty menu handlers using switch statement:
import java.util.Scanner;
public class BankAccount {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int userChoice;
boolean quit = false;
do {
System.out.println("1. Deposit money");
System.out.println("2. Withdraw money");
System.out.println("3. Check balance");
System.out.print("Your choice, 0 to quit: ");
userChoice = in.nextInt();
switch (userChoice) {
case 1:
// deposit money
break;
case 2:
// withdraw money
break;
case 3:
// check balance
break;
case 0:
quit = true;
break;
default:
System.out.println("Wrong choice.");
break;
}
System.out.println();
} while (!quit);
System.out.println("Bye!");
}
}
1. Deposit money
2. Withdraw money
3. Check balance
Your choice, 0 to quit: 1
1. Deposit money
2. Withdraw money
3. Check balance
Your choice, 0 to quit: 4
Wrong choice.
1. Deposit money
2. Withdraw money
3. Check balance
Your choice, 0 to quit: 0
Bye!
Bank account's functionality
It's time to add principal functionality to the program:
 declare variable balance, default value 0f;
 add deposit/withdraw/check balance functionality.
import java.util.Scanner;
public class BankAccount {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int userChoice;
boolean quit = false;
float balance = 0f;
do {
System.out.println("1. Deposit money");
System.out.println("2. Withdraw money");
System.out.println("3. Check balance");
System.out.print("Your choice, 0 to quit: ");
userChoice = in.nextInt();
switch (userChoice) {
case 1:
float amount;
System.out.print("Amount to deposit: ");
amount = in.nextFloat();
balance += amount;
break;
case 2:
System.out.print("Amount to withdraw: ");
amount = in.nextFloat();
balance -= amount;
break;
case 3:
System.out.println("Your balance: $" + balance);
break;
case 0:
quit = true;
break;
default:
System.out.println("Wrong choice.");
break;
}
System.out.println();
} while (!quit);
System.out.println("Bye!");
}
}
1. Deposit money
2. Withdraw money
3. Check balance
Your choice, 0 to quit: 1
Amount to deposit: 100
1. Deposit money
2. Withdraw money
3. Check balance
Your choice, 0 to quit: 2
Amount to withdraw: 50
1. Deposit money
2. Withdraw money
3. Check balance
Your choice, 0 to quit: 3
Your balance: $50.0
1. Deposit money
2. Withdraw money
3. Check balance
Your choice, 0 to quit: 0
Bye!
Safety checks
At the moment program allows to withdraw more than actual balance, deposit and withdraw
negative amounts of money. Let's fix it, using if statement and conditions combinations.
import java.util.Scanner;
public class BankAccount {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int userChoice;
boolean quit = false;
float balance = 0f;
do {
System.out.println("1. Deposit money");
System.out.println("2. Withdraw money");
System.out.println("3. Check balance");
System.out.print("Your choice, 0 to quit: ");
userChoice = in.nextInt();
switch (userChoice) {
case 1:
float amount;
System.out.print("Amount to deposit: ");
amount = in.nextFloat();
if (amount <= 0)
System.out.println("Can't deposit nonpositive
amount.");
else {
balance += amount;
System.out.println("$" + amount + " has been
deposited.");
}
break;
case 2:
System.out.print("Amount to withdraw: ");
amount = in.nextFloat();
if (amount <= 0 || amount > balance)
System.out.println("Withdrawal can't be
completed.");
else {
balance -= amount;
System.out.println("$" + amount + " has been
withdrawn.");
}
break;
case 3:
System.out.println("Your balance: $" + balance);
break;
case 0:
quit = true;
break;
default:
System.out.println("Wrong choice.");
break;
}
System.out.println();
} while (!quit);
System.out.println("Bye!");
}
}
1. Deposit money
2. Withdraw money
3. Check balance
Your choice, 0 to quit: 1
Amount to deposit: -45
Can't deposit nonpositive amount.
1. Deposit money
2. Withdraw money
3. Check balance
Your choice, 0 to quit: 2
Amount to withdraw: 45
Withdrawal can't be completed.
1. Deposit money
2. Withdraw money
3. Check balance
Your choice, 0 to quit: 2
Amount to withdraw: -45
Withdrawal can't be completed.
1. Deposit money
2. Withdraw money
3. Check balance
Your choice, 0 to quit: 0
Bye!
Final source
Program is complete. Below you can find final source code.
import java.util.Scanner;
public class BankAccount {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int userChoice;
boolean quit = false;
float balance = 0f;
do {
System.out.println("1. Deposit money");
System.out.println("2. Withdraw money");
System.out.println("3. Check balance");
System.out.print("Your choice, 0 to quit: ");
userChoice = in.nextInt();
switch (userChoice) {
case 1:
float amount;
System.out.print("Amount to deposit: ");
amount = in.nextFloat();
if (amount <= 0)
System.out.println("Can't deposit nonpositive
amount.");
else {
balance += amount;
System.out.println("$" + amount + " has been
deposited.");
}
break;
case 2:
System.out.print("Amount to withdraw: ");
amount = in.nextFloat();
if (amount <= 0 || amount > balance)
System.out.println("Withdrawal can't be
completed.");
else {
balance -= amount;
System.out.println("$" + amount + " has been
withdrawn.");
}
break;
case 3:
System.out.println("Your balance: $" + balance);
break;
case 0:
quit = true;
break;
default:
System.out.println("Wrong choice.");
break;
}
System.out.println();
} while (!quit);
System.out.println("Bye!");
}
}

More Related Content

What's hot

Use of artificial neural networks to identify fake profiles
Use of artificial neural networks to identify fake profilesUse of artificial neural networks to identify fake profiles
Use of artificial neural networks to identify fake profilesVenkat Projects
 
JPC#8 Introduction to Java Programming
JPC#8 Introduction to Java ProgrammingJPC#8 Introduction to Java Programming
JPC#8 Introduction to Java ProgrammingPathomchon Sriwilairit
 
ma project
ma projectma project
ma projectAisu
 
Best Java Problems and Solutions
Best Java Problems and SolutionsBest Java Problems and Solutions
Best Java Problems and SolutionsJava Projects
 

What's hot (6)

Use of artificial neural networks to identify fake profiles
Use of artificial neural networks to identify fake profilesUse of artificial neural networks to identify fake profiles
Use of artificial neural networks to identify fake profiles
 
Cs in science_guides
Cs in science_guidesCs in science_guides
Cs in science_guides
 
JPC#8 Introduction to Java Programming
JPC#8 Introduction to Java ProgrammingJPC#8 Introduction to Java Programming
JPC#8 Introduction to Java Programming
 
Ann
AnnAnn
Ann
 
ma project
ma projectma project
ma project
 
Best Java Problems and Solutions
Best Java Problems and SolutionsBest Java Problems and Solutions
Best Java Problems and Solutions
 

Viewers also liked

Lab exp (declaring classes)
Lab exp (declaring classes)Lab exp (declaring classes)
Lab exp (declaring classes)Daman Toor
 
Lab exam setb_5_5_2015
Lab exam setb_5_5_2015Lab exam setb_5_5_2015
Lab exam setb_5_5_2015Daman Toor
 
Lab exp (creating classes and objects)
Lab exp (creating classes and objects)Lab exp (creating classes and objects)
Lab exp (creating classes and objects)Daman Toor
 
Parking ticket simulator program
Parking ticket simulator programParking ticket simulator program
Parking ticket simulator programDaman Toor
 
Lab exp declaring arrays)
Lab exp declaring arrays)Lab exp declaring arrays)
Lab exp declaring arrays)Daman Toor
 
Lab exam 5_5_15
Lab exam 5_5_15Lab exam 5_5_15
Lab exam 5_5_15Daman Toor
 
Java assignment 1
Java assignment 1Java assignment 1
Java assignment 1Daman Toor
 

Viewers also liked (8)

Lab exp (declaring classes)
Lab exp (declaring classes)Lab exp (declaring classes)
Lab exp (declaring classes)
 
Lab exam setb_5_5_2015
Lab exam setb_5_5_2015Lab exam setb_5_5_2015
Lab exam setb_5_5_2015
 
Lab exp (creating classes and objects)
Lab exp (creating classes and objects)Lab exp (creating classes and objects)
Lab exp (creating classes and objects)
 
Parking ticket simulator program
Parking ticket simulator programParking ticket simulator program
Parking ticket simulator program
 
Lab exp declaring arrays)
Lab exp declaring arrays)Lab exp declaring arrays)
Lab exp declaring arrays)
 
Lab exam 5_5_15
Lab exam 5_5_15Lab exam 5_5_15
Lab exam 5_5_15
 
Uta005
Uta005Uta005
Uta005
 
Java assignment 1
Java assignment 1Java assignment 1
Java assignment 1
 

Similar to Practice

Lab101.pptx
Lab101.pptxLab101.pptx
Lab101.pptxKimVeeL
 
ch05-program-logic-indefinite-loops.ppt
ch05-program-logic-indefinite-loops.pptch05-program-logic-indefinite-loops.ppt
ch05-program-logic-indefinite-loops.pptMahyuddin8
 
Repetition Structure.pptx
Repetition Structure.pptxRepetition Structure.pptx
Repetition Structure.pptxrhiene05
 
Lab01.pptx
Lab01.pptxLab01.pptx
Lab01.pptxKimVeeL
 
I am constantly getting errors and cannot figure this out. Please he.pdf
I am constantly getting errors and cannot figure this out. Please he.pdfI am constantly getting errors and cannot figure this out. Please he.pdf
I am constantly getting errors and cannot figure this out. Please he.pdfallystraders
 
Programming in Java: Arrays
Programming in Java: ArraysProgramming in Java: Arrays
Programming in Java: ArraysMartin Chapman
 
Example of JAVA Program
Example of JAVA ProgramExample of JAVA Program
Example of JAVA ProgramTrenton Asbury
 
when I compile to get the survey title the overload constructor asks.docx
when I compile to get the survey title the overload constructor asks.docxwhen I compile to get the survey title the overload constructor asks.docx
when I compile to get the survey title the overload constructor asks.docxlashandaotley
 
import java.util.;public class Program{public static void.pdf
import java.util.;public class Program{public static void.pdfimport java.util.;public class Program{public static void.pdf
import java.util.;public class Program{public static void.pdfoptokunal1
 
Please observe the the code and validations of user inputs.import .pdf
Please observe the the code and validations of user inputs.import .pdfPlease observe the the code and validations of user inputs.import .pdf
Please observe the the code and validations of user inputs.import .pdfapexjaipur
 
Create a menu-driven program that will accept a collection of non-ne.pdf
Create a menu-driven program that will accept a collection of non-ne.pdfCreate a menu-driven program that will accept a collection of non-ne.pdf
Create a menu-driven program that will accept a collection of non-ne.pdfrajeshjangid1865
 
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.pdfFashionColZone
 

Similar to Practice (15)

Lab101.pptx
Lab101.pptxLab101.pptx
Lab101.pptx
 
ch05-program-logic-indefinite-loops.ppt
ch05-program-logic-indefinite-loops.pptch05-program-logic-indefinite-loops.ppt
ch05-program-logic-indefinite-loops.ppt
 
Repetition Structure.pptx
Repetition Structure.pptxRepetition Structure.pptx
Repetition Structure.pptx
 
Lab01.pptx
Lab01.pptxLab01.pptx
Lab01.pptx
 
I am constantly getting errors and cannot figure this out. Please he.pdf
I am constantly getting errors and cannot figure this out. Please he.pdfI am constantly getting errors and cannot figure this out. Please he.pdf
I am constantly getting errors and cannot figure this out. Please he.pdf
 
07-Basic-Input-Output.ppt
07-Basic-Input-Output.ppt07-Basic-Input-Output.ppt
07-Basic-Input-Output.ppt
 
Programming in Java: Arrays
Programming in Java: ArraysProgramming in Java: Arrays
Programming in Java: Arrays
 
Ch5(loops)
Ch5(loops)Ch5(loops)
Ch5(loops)
 
Comp102 lec 6
Comp102   lec 6Comp102   lec 6
Comp102 lec 6
 
Example of JAVA Program
Example of JAVA ProgramExample of JAVA Program
Example of JAVA Program
 
when I compile to get the survey title the overload constructor asks.docx
when I compile to get the survey title the overload constructor asks.docxwhen I compile to get the survey title the overload constructor asks.docx
when I compile to get the survey title the overload constructor asks.docx
 
import java.util.;public class Program{public static void.pdf
import java.util.;public class Program{public static void.pdfimport java.util.;public class Program{public static void.pdf
import java.util.;public class Program{public static void.pdf
 
Please observe the the code and validations of user inputs.import .pdf
Please observe the the code and validations of user inputs.import .pdfPlease observe the the code and validations of user inputs.import .pdf
Please observe the the code and validations of user inputs.import .pdf
 
Create a menu-driven program that will accept a collection of non-ne.pdf
Create a menu-driven program that will accept a collection of non-ne.pdfCreate a menu-driven program that will accept a collection of non-ne.pdf
Create a menu-driven program that will accept a collection of non-ne.pdf
 
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
 

More from Daman Toor

Identifiers, keywords and types
Identifiers, keywords and typesIdentifiers, keywords and types
Identifiers, keywords and typesDaman Toor
 
Classes & object
Classes & objectClasses & object
Classes & objectDaman Toor
 

More from Daman Toor (7)

String slide
String slideString slide
String slide
 
Nested class
Nested classNested class
Nested class
 
Inheritance1
Inheritance1Inheritance1
Inheritance1
 
Inheritance
InheritanceInheritance
Inheritance
 
Operators
OperatorsOperators
Operators
 
Identifiers, keywords and types
Identifiers, keywords and typesIdentifiers, keywords and types
Identifiers, keywords and types
 
Classes & object
Classes & objectClasses & object
Classes & object
 

Recently uploaded

Class 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdfClass 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdfakmcokerachita
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsanshu789521
 
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxContemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxRoyAbrique
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Sapana Sha
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Celine George
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfSumit Tiwari
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxpboyjonauth
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformChameera Dedduwage
 
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...M56BOOKSTORE PRODUCT/SERVICE
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application ) Sakshi Ghasle
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13Steve Thomason
 
MENTAL STATUS EXAMINATION format.docx
MENTAL     STATUS EXAMINATION format.docxMENTAL     STATUS EXAMINATION format.docx
MENTAL STATUS EXAMINATION format.docxPoojaSen20
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionSafetyChain Software
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentInMediaRes1
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdfSoniaTolstoy
 

Recently uploaded (20)

Class 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdfClass 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdf
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha elections
 
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxContemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptx
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy Reform
 
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application )
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13
 
MENTAL STATUS EXAMINATION format.docx
MENTAL     STATUS EXAMINATION format.docxMENTAL     STATUS EXAMINATION format.docx
MENTAL STATUS EXAMINATION format.docx
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory Inspection
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media Component
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 

Practice

  • 1. Practice. Developing "number guessing game" step by step In the lesson we will practise using the basic Java tools learned in previous articles. To do it let's develop the "Guess game". Its rules are as follows:  Computer proposes a number from 1 to 1000.  Human player tries to guess it. One enters a guess and computer tells if the number matches or it is smaller/greater than the proposed one.  Game continues, until player guesses the number. Step 1. Class & main function Let's call the class "NumberGuessingGame" and add empty main function. It's completely valid program you can compile and run, but it doesn't print anything to the console yet. public class NumberGuessingGame { public static void main(String[] args) { } } Step 2. Secret number To propose a secret number, we declare a variable secretNumber of type int and use Math.random() function to give it random value in range 1..1000. public class NumberGuessingGame { public static void main(String[] args) { int secretNumber; secretNumber = (int) (Math.random() * 999 + 1); System.out.println("Secret number is " + secretNumber); // to be removed later }
  • 2. } Secret number is 230 Don't worry, if you don't understand how things with random work. It's not a subject of the lesson, so just believe it. Note, that program exposes secret number to player at the moment, but we will remove the line printing the proposal in the final version. Step 3. Asking user for a guess In order to get input from user, we declare another variable guess of type int. Code, reading input from user is not to be discussed in detail here, so take it on trust. import java.util.Scanner; public class NumberGuessingGame { public static void main(String[] args) { int secretNumber; secretNumber = (int) (Math.random() * 999 + 1); System.out.println("Secret number is " + secretNumber); // to be removed // later Scanner keyboard = new Scanner(System.in); int guess; System.out.print("Enter a guess: "); guess = keyboard.nextInt(); System.out.println("Your guess is " + guess); } } Secret number is 78 Enter a guess: 555 Your guess is 555
  • 3. Step 4. Checking if guess is right Now let's check if human player's guess is right. If so program should print corresponding message. Otherwise, tell user that a guess is smaller/greater than the proposed number. To test the program let's try all three cases (remember that we peeked the secret number). import java.util.Scanner; public class NumberGuessingGame { public static void main(String[] args) { int secretNumber; secretNumber = (int) (Math.random() * 999 + 1); System.out.println("Secret number is " + secretNumber); // to be removed // later Scanner keyboard = new Scanner(System.in); int guess; System.out.print("Enter a guess: "); guess = keyboard.nextInt(); System.out.println("Your guess is " + guess); if (guess == secretNumber) System.out.println("Your guess is correct. Congratulations!"); else if (guess < secretNumber) System.out .println("Your guess is smaller than the secret number."); else if (guess > secretNumber) System.out
  • 4. .println("Your guess is greater than the secret number."); } } Secret number is 938 Enter a guess: 938 Your guess is 938 Your guess is correct. Congratulations! Secret number is 478 Enter a guess: 222 Your guess is 222 Your guess is smaller than the secret number. Secret number is 559 Enter a guess: 777 Your guess is 777 Your guess is greater than the secret number. Things seem to be working ok. Step 5. Add tries At the moment user has only one attempt to guess a number, which is, obvious, not sufficient. Our next step is about giving user as many attempts as one needs. For this purpose let's use do- while loop, because user must enter a guess at least once. import java.util.Scanner; public class NumberGuessingGame { public static void main(String[] args) { int secretNumber; secretNumber = (int) (Math.random() * 999 + 1); System.out.println("Secret number is " + secretNumber); // to be removed // later Scanner keyboard = new Scanner(System.in);
  • 5. int guess; do { System.out.print("Enter a guess: "); guess = keyboard.nextInt(); System.out.println("Your guess is " + guess); if (guess == secretNumber) System.out.println("Your guess is correct. Congratulations!"); else if (guess < secretNumber) System.out .println("Your guess is smaller than the secret number."); else if (guess > secretNumber) System.out .println("Your guess is greater than the secret number."); } while (guess != secretNumber); } } Secret number is 504 Enter a guess: 777 Your guess is 777 Your guess is greater than the secret number. Enter a guess: 333 Your guess is 333 Your guess is smaller than the secret number. Enter a guess: 504
  • 6. Your guess is 504 Your guess is correct. Congratulations! Final step. Make it glow Just before we consider the program to be complete, let's remove the code, used for debug purposes. import java.util.Scanner; public class NumberGuessingGame { public static void main(String[] args) { int secretNumber; secretNumber = (int) (Math.random() * 999 + 1); Scanner keyboard = new Scanner(System.in); int guess; do { System.out.print("Enter a guess (1-1000): "); guess = keyboard.nextInt(); if (guess == secretNumber) System.out.println("Your guess is correct. Congratulations!"); else if (guess < secretNumber) System.out .println("Your guess is smaller than the secret number."); else if (guess > secretNumber) System.out .println("Your guess is greater than the secret number.");
  • 7. } while (guess != secretNumber); } } Enter a guess (1-1000): 500 Your guess is greater than the secret number. Enter a guess (1-1000): 250 Your guess is smaller than the secret number. Enter a guess (1-1000): 375 Your guess is smaller than the secret number. Enter a guess (1-1000): 437 Your guess is smaller than the secret number. Enter a guess (1-1000): 468 Your guess is smaller than the secret number. Enter a guess (1-1000): 484 Your guess is greater than the secret number. Enter a guess (1-1000): 476 Your guess is greater than the secret number. Enter a guess (1-1000): 472 Your guess is correct. Congratulations! Extra tasks If you would like to practise on your own, there are suggestions of possible improvements: 1. Check, if user enters the number in range 1.1000 and force one to re-enter a guess in case it is out of bounds. 2. Limit the number of attempts. 3. Add more than one round and wins/loses score.
  • 8. In current practice lesson we are going to develop a menu-driven application to manage simple bank account. It supports following operations:  deposit money;  withdraw money;  check balance. Application is driven by a text menu. Skeleton First of all, let's create an application to run infinitely and ask user for a choice, until quit option is chosen: import java.util.Scanner; public class BankAccount { public static void main(String[] args) { Scanner in = new Scanner(System.in); int userChoice; boolean quit = false; do { System.out.print("Your choice, 0 to quit: "); userChoice = in.nextInt(); if (userChoice == 0) quit = true; } while (!quit); } } Your choice, 0 to quit: 2 Your choice, 0 to quit: 6
  • 9. Your choice, 0 to quit: 0 Bye! Draw your attention to boolean variable quit, which is responsible for correct loop interruption. What a reason to declare additional variable, if one can check exit condition right in while statement? It's the matter of good programming style. Later you'll see why. Menu Now let's add a menu and empty menu handlers using switch statement: import java.util.Scanner; public class BankAccount { public static void main(String[] args) { Scanner in = new Scanner(System.in); int userChoice; boolean quit = false; do { System.out.println("1. Deposit money"); System.out.println("2. Withdraw money"); System.out.println("3. Check balance"); System.out.print("Your choice, 0 to quit: "); userChoice = in.nextInt(); switch (userChoice) { case 1: // deposit money break; case 2: // withdraw money
  • 10. break; case 3: // check balance break; case 0: quit = true; break; default: System.out.println("Wrong choice."); break; } System.out.println(); } while (!quit); System.out.println("Bye!"); } } 1. Deposit money 2. Withdraw money 3. Check balance Your choice, 0 to quit: 1 1. Deposit money 2. Withdraw money 3. Check balance Your choice, 0 to quit: 4
  • 11. Wrong choice. 1. Deposit money 2. Withdraw money 3. Check balance Your choice, 0 to quit: 0 Bye! Bank account's functionality It's time to add principal functionality to the program:  declare variable balance, default value 0f;  add deposit/withdraw/check balance functionality. import java.util.Scanner; public class BankAccount { public static void main(String[] args) { Scanner in = new Scanner(System.in); int userChoice; boolean quit = false; float balance = 0f; do { System.out.println("1. Deposit money"); System.out.println("2. Withdraw money"); System.out.println("3. Check balance"); System.out.print("Your choice, 0 to quit: ");
  • 12. userChoice = in.nextInt(); switch (userChoice) { case 1: float amount; System.out.print("Amount to deposit: "); amount = in.nextFloat(); balance += amount; break; case 2: System.out.print("Amount to withdraw: "); amount = in.nextFloat(); balance -= amount; break; case 3: System.out.println("Your balance: $" + balance); break; case 0: quit = true; break; default: System.out.println("Wrong choice."); break; } System.out.println(); } while (!quit); System.out.println("Bye!");
  • 13. } } 1. Deposit money 2. Withdraw money 3. Check balance Your choice, 0 to quit: 1 Amount to deposit: 100 1. Deposit money 2. Withdraw money 3. Check balance Your choice, 0 to quit: 2 Amount to withdraw: 50 1. Deposit money 2. Withdraw money 3. Check balance Your choice, 0 to quit: 3 Your balance: $50.0 1. Deposit money 2. Withdraw money 3. Check balance Your choice, 0 to quit: 0
  • 14. Bye! Safety checks At the moment program allows to withdraw more than actual balance, deposit and withdraw negative amounts of money. Let's fix it, using if statement and conditions combinations. import java.util.Scanner; public class BankAccount { public static void main(String[] args) { Scanner in = new Scanner(System.in); int userChoice; boolean quit = false; float balance = 0f; do { System.out.println("1. Deposit money"); System.out.println("2. Withdraw money"); System.out.println("3. Check balance"); System.out.print("Your choice, 0 to quit: "); userChoice = in.nextInt(); switch (userChoice) { case 1: float amount; System.out.print("Amount to deposit: "); amount = in.nextFloat(); if (amount <= 0)
  • 15. System.out.println("Can't deposit nonpositive amount."); else { balance += amount; System.out.println("$" + amount + " has been deposited."); } break; case 2: System.out.print("Amount to withdraw: "); amount = in.nextFloat(); if (amount <= 0 || amount > balance) System.out.println("Withdrawal can't be completed."); else { balance -= amount; System.out.println("$" + amount + " has been withdrawn."); } break; case 3: System.out.println("Your balance: $" + balance); break; case 0: quit = true; break; default: System.out.println("Wrong choice.");
  • 16. break; } System.out.println(); } while (!quit); System.out.println("Bye!"); } } 1. Deposit money 2. Withdraw money 3. Check balance Your choice, 0 to quit: 1 Amount to deposit: -45 Can't deposit nonpositive amount. 1. Deposit money 2. Withdraw money 3. Check balance Your choice, 0 to quit: 2 Amount to withdraw: 45 Withdrawal can't be completed. 1. Deposit money 2. Withdraw money 3. Check balance
  • 17. Your choice, 0 to quit: 2 Amount to withdraw: -45 Withdrawal can't be completed. 1. Deposit money 2. Withdraw money 3. Check balance Your choice, 0 to quit: 0 Bye! Final source Program is complete. Below you can find final source code. import java.util.Scanner; public class BankAccount { public static void main(String[] args) { Scanner in = new Scanner(System.in); int userChoice; boolean quit = false; float balance = 0f; do { System.out.println("1. Deposit money"); System.out.println("2. Withdraw money");
  • 18. System.out.println("3. Check balance"); System.out.print("Your choice, 0 to quit: "); userChoice = in.nextInt(); switch (userChoice) { case 1: float amount; System.out.print("Amount to deposit: "); amount = in.nextFloat(); if (amount <= 0) System.out.println("Can't deposit nonpositive amount."); else { balance += amount; System.out.println("$" + amount + " has been deposited."); } break; case 2: System.out.print("Amount to withdraw: "); amount = in.nextFloat(); if (amount <= 0 || amount > balance) System.out.println("Withdrawal can't be completed."); else { balance -= amount; System.out.println("$" + amount + " has been withdrawn."); }
  • 19. break; case 3: System.out.println("Your balance: $" + balance); break; case 0: quit = true; break; default: System.out.println("Wrong choice."); break; } System.out.println(); } while (!quit); System.out.println("Bye!"); } }