SlideShare a Scribd company logo
Java   small steps - 2019
JAVA CODING EXERCISES
Practise ANSWERS to Exercise Questions
Java Programming 7th Edition by Joyce Farrell
Chapter 2:
Chapter 3: 3, 4, 6, 7, 8, 9, 10, 11, 12, C1, 13, 14,
Chapter 4: EX1, EX2, 1, 2, 3, 4, 6, 5, 7
Chapter 5: 1, 2, 3, 4, 5, 6, 7, 8, 9
Chapter 6: EXL1, EXL2, 3, 1, 2, 5, 6, 4, 9, 10
Chapter 7: EXL1, EXL2, EX3, EX4
Chapter 8: 1,
Chapter 9: EX1, EX2, EX3, EX4, EX5
Chapter 12: EX1, EX2, EX3, EX4, EX5
Chapter 14: EX1,
Chapter 16: EX1,
Others: EX1, EX2, EX3, EX4, EX5, EX6, EX7, EX8, EX9, EX10, EX11,
EX12 , EX13, EX14, EX15. EX16, EX17, EX18, EX19, EX20, EX21
Additional Examples from:
Java for Kids – NetBeans8 Programming Tutorial 8th Edition – ©Philip Conrod
& Lou Tylee. ©2015 Kidware Software LLC; www.kidwaresoftware.com
Source: Beginning Java - Philip Conrod & Lou Tylee
©2015 Kidware Software LLC; www.kidwaresoftware.com
(NOTE:
All
these
practice
files
must
be
in
the
same
folder
or
package
because
some
classes
are
dependent
on
others.)
QUESTION
Write a Java class that declares a named constant that holds the number of feet in a
mile: 5,280. Also declare a variable to represent the distance in miles between your
house and your uncle’s house. Assign an appropriate value to the variable— for
example, 8.5. Compute and display the distance to your uncle’s house in both miles
and feet. Display explanatory text with the values—for example, The distance to my
uncle's house is 8.5 miles or 44880.0 feet. Save the class as
MilesToFeet.java.
public class MilesToFeet {
public static void main(String[] args) {
double distanceInMiles = 8.5;
final float MILES_TO_FEET = 5280;
double distanceInFeet = distanceInMiles * MILES_TO_FEET;
//float distanceInMiles = 8.5;
// distanceInFeet = float (MILE_TO_FEET * distanceInMiles);
System.out.println("Distance in Miles " + distanceInMiles);
System.out.println("Distance in feet " + distanceInFeet);
} }
Miles to Feet Interactive
Convert the MilesToFeet class to an interactive application. Instead of assigning a
value to the distance, accept the value from the user as input. Save the revised class
as MilesToFeetInteractive.java.
import javax.swing.JOptionPane;
public class MilesToFeetInteractive {
public static void main(String[] args) {
String milesString; //declare milesString as String variable
double distanceInFeet; //declare distanceInFeet as a double variable
final float MILES_TO_FEET = 5280; //declare MILES_TO_FLEET (comversion
factor)as a float varaible with a constant value of 5280
//the next line of code displays a dialog box for inputing the distance in miles
milesString = JOptionPane.showInputDialog(null, "Distance in Miles ", "Enter
distance in miles", JOptionPane.INFORMATION_MESSAGE);
//the next line is the code for doing the conversion
distanceInFeet = Double.parseDouble(milesString) * MILES_TO_FEET;
//the next line of code displays an information box with the answer!
JOptionPane.showMessageDialog(null, "Distance in feet is " + distanceInFeet);
}}
5a Write a Java class that declares a named constant that represents next
year’s anticipated 10 percent increase in sales for each division of a company.
(You can represent 10 percent as 0.10.) Also declare variables to represent
this year’s sales total in dollars for the North and South divisions. Assign
appropriate values to the variables—for example, 4000 and 5500. Compute
and display, with explanatory text, next year
public class ProjectedSales {
public static void main(String[] args) {
final double PERCENT_INCREASE = 0.10; //10% annual increase
declared as a fixed double CONSTANT
int divNorth, divSouth; //This year's sales declared as integers
divNorth = 4000; //Value of this year's sales for division North
divSouth = 5500; //Value of this year's sales for South division
double projectedDivNorth, projectedDivSouth; //projected sales for next year
declared as double variables
projectedDivNorth = (1 + PERCENT_INCREASE) * divNorth;
//CALCULATING NEXT YEAR PROJECTED SALES FOR NORTH DIVISION
projectedDivSouth = (1 + PERCENT_INCREASE) * divSouth;
//CALCULATING NEXT YEAR PROJECTED SALES FOR SOUTH DIVISION
System.out.println("Projected next year sales for North division " +
projectedDivNorth);
System.out.println("Projected next year sales for South division " +
projectedDivSouth);
}
}
5b. Convert the ProjectedSales class to an interactive application. Instead of
assigning values to the North and South current year sales variables, accept them
from the user as input. Save the revised class as ProjectedSalesInteractive.java.
import javax.swing.JOptionPane; //import javax swing JOption method
public class ProjectedSalesInteractive { //the name of the application is
ProjectedSalesIncrease
public static void main(String[] args) { //the start of the main program
final double PERCENT_INCREASE = 0.10; //10% projected increase declared as
a constant variable = 0.10
String percentIncrease; //the percentage increase declared as aString
double projectedDivNorth, projectedDivSouth; //next year projected sales declared
as a double variable
//the code below opens a dialog box where we can enter the value for this year's
North division sales as a String variable
percentIncrease = JOptionPane.showInputDialog(null, "This years sales for North
division in $ is ",
"North Division ", JOptionPane.INFORMATION_MESSAGE);
//the codes below executes and display the value of projected next year sales for
South division as a double
projectedDivNorth = Double.parseDouble(percentIncrease) * (1 +
PERCENT_INCREASE);
JOptionPane.showMessageDialog(null, "Projected North division sales for next
year is " + projectedDivNorth);
percentIncrease = JOptionPane.showInputDialog(null, "This years sales for South
division in $ is ",
"South Division ", JOptionPane.INFORMATION_MESSAGE);
//the codes below executes and display the value of projected next year sales for
South division as a double
projectedDivSouth = Double.parseDouble(percentIncrease) * (1+
PERCENT_INCREASE);
JOptionPane.showMessageDialog(null, "Projected South division sales is " +
projectedDivSouth);
} }
6. a. Write a class that declares a variable named inches that holds a length in
inches, and assign a value. Display the value in feet and inches; for example,
86 inches becomes 7 feet and 2 inches. Be sure to use a named constant where
appropriate. Save the class as InchesToFeet.java.
public class InchesToFeet {
public static void main(String[] args) {
//inches to feet (12 inches equals 1 foot)
//declare integer variable INCHES_TO_FEET with constant value
final int INCHES_TO_FEET_FACTOR = 12;
// declare lengthInInches as integer with an initial value of 81 feet
int lengthInInches = 72;
//declare lengthInInches, LengthInFeetPart, lengthInInchesPart as integers
//lengthInFeetPart is the whole part of the division representing # of feet
//lengthInInchesPart is the remainder after the division is made - using the %
operator
int lengthInFeetPart, lengthInInchesPart;
//integer division of feet by 12 to give feet (feet/12)
lengthInFeetPart = lengthInInches / (INCHES_TO_FEET_FACTOR);
//mod, that is % division to give the inchees part
lengthInInchesPart = lengthInInches % INCHES_TO_FEET_FACTOR;
//print the whole feet part of the conversion
System.out.print(lengthInFeetPart + " feet ");
//print the inches part of the conversion by the side of the feet part on the same
line.
System.out.print(lengthInInchesPart + " inches ");
}
}
6b. Write an interactive version of the InchesToFeet class that accepts the
inches value from a user. Save the class as inchesToFeetInteractive.java.
import javax.swing.JOptionPane;
public class InchesToFeetInteractive { //Converting from Inchees to Feet
public static void main(String[] args) { //the main program starts here
//12 inches = 1 foot, this is a CONSTANT integer declaration
final int INCHES_TO_FEET_FACTOR = 12;
//the length to be entered into the dialog box declared as a string value
String inches;
//all measured length are declared as integers
int lengthInInches, lengthInInchesPart, lengthInFeetPart;
//the measured length in inches is entered into the dialog box
inches = JOptionPane.showInputDialog(null, "Length in inches", "Enter length in
inches",
JOptionPane.INFORMATION_MESSAGE);
//the length entered into the dialog box as string is parsed into an integer
lengthInInches = Integer.parseInt(inches);
//inches is converted into feet - this is the whole part of the division
lengthInFeetPart = lengthInInches / (INCHES_TO_FEET_FACTOR);
//the mod that is % division of the measured length = the inches part
lengthInInchesPart = lengthInInches % INCHES_TO_FEET_FACTOR;
//Message box displays the measured length in feet and inches
JOptionPane.showMessageDialog(null, "Length is " + lengthInFeetPart + " feet
"
+ lengthInInchesPart + " inches");
//NOTE THAT THIS WILL NOT WORK FOR FLOAT OR DECIMAL NUMBERS
}
}
11. Write a program that accepts a temperature in Fahrenheit from a user and
converts it to Celsius by subtracting 32 from the Fahrenheit value and
multiplying the result by 5/9. Display both values. Save the class as
FahrenheitToCelsius.java.
public class FahrenheitToCelsius {
public static void main(String[] args) {
float temperatureInFahrenheit = 900;
float temperatureInCelsius = 5 * (temperatureInFahrenheit - 32)/9;
System.out.println(temperatureInFahrenheit + "F is equal to " +
temperatureInCelsius + "C");
}
}
INTERACTIVE VERSION
import javax.swing.JOptionPane;
public class FahrenheitToCelsiusInteractive {
public static void main(String[] args) {
float temperatureInFahrenheit;
String fahrenheitString;
fahrenheitString = JOptionPane.showInputDialog(null, "Temperature in Fahrenheit ",
"Enter temperature in Fahrenheit",
JOptionPane.INFORMATION_MESSAGE);
temperatureInFahrenheit = Float.parseFloat(fahrenheitString);
float temperatureInCelsius = 5 * (temperatureInFahrenheit - 32)/9;
JOptionPane.showMessageDialog(null, temperatureInFahrenheit + " F" + " is equal to
"
+ temperatureInCelsius + " C");
}
}
8a. Meadowdale Dairy Farm sells organic brown eggs to local customers. They
charge $3.25 for a dozen eggs, or 45 cents for individual eggs that are not part
of a dozen. Write a class that prompts a user for the number of eggs in the
order and then display the amount owed with a full explanation. For example,
typical output might be, “You ordered 27 eggs. That’s 2 dozen at $3.25 per
dozen and 3 loose eggs at 45.0 cents each for a total of $7.85.” Save the class
as Eggs.java.
public class Eggs {
public static void main(String[] arguments) {
//price per dozen eggs = $3.25
final double PRICE_PER_DOZEN = 3.25;
//price per single unit egg = 45cents ($0.45)
final double PRICE_PER_UNIT_EGGS = 0.45;
// a dozen = 12
final int ONE_DOZEN = 12;
//all the variables above are declared as constants.
//Per dozen price, per unit price, total amount paid
//declared as double variables
double costForDozens, costForUnits, totalAmount;
//#of eggs purchased, #of dozens, # of single units
//declared as integers
int numberOfEggsPurchased = 27;
int numberOfDozens, numberOfUnitEggs;
//how many dozens are in the quantity purchased?
numberOfDozens = numberOfEggsPurchased / 12;
//how many single units are left after getting the 3 of dozens in the purchase?
numberOfUnitEggs = numberOfEggsPurchased % 12;
//amount paid for the # of dozens portion.
costForDozens = numberOfDozens * PRICE_PER_DOZEN;
//amount paid for the single eggss portion
costForUnits = numberOfUnitEggs * PRICE_PER_UNIT_EGGS;
//below is the total amount paid in $
totalAmount = costForDozens + costForUnits;
//message displayed at the end of the calculation
System.out.print(" You ordered 27 eggs. That is ");
System.out.print(numberOfDozens +" dozens ");
System.out.print(" at $3.25 per dozen and ");
//System.out.print(" You ordered 27 eggs. That is " + numberOfDozens " at
$3,25 per dozen ");
System.out.print(numberOfUnitEggs + " eggs at 45.0 cents each for a total of $"
+ totalAmount + (" "));
}
}
8b. INTERACTIVE VERSION OF 8a
import javax.swing.JOptionPane;
public class EggsInteractive {
public static void main(String[] args) {
//price per dozen eggs = $3.25
final double PRICE_PER_DOZEN = 3.25;
//price per single unit egg = 45cents ($0.45)
final double PRICE_PER_UNIT_EGGS = 0.45;
// a dozen = 12
final int ONE_DOZEN = 12;
//all the variables above are declared as constants.
//Per dozen price, per unit price, total amount paid
//declared as double variables
double costForDozens, costForUnits, totalAmount;
String howManyEggs; //the number of eggs ordered declared as a string
int numberOfEggsPurchased; // number of eggs ordered as an integer
//the number of eggs entered into the dialog box as a string
howManyEggs = JOptionPane.showInputDialog(null, "Number of eggs ordered ",
"Enter the number of eggs you want to buy.",
JOptionPane.INFORMATION_MESSAGE);
//#of eggs purchased, #of dozens, # of single units
//all declared as integers
numberOfEggsPurchased = Integer.parseInt(howManyEggs);
int numberOfDozens, numberOfUnitEggs;
//how many dozens are in the quantity purchased?
numberOfDozens = numberOfEggsPurchased / 12;
//how many single units are left after getting the 3 of dozens in the purchase?
numberOfUnitEggs = numberOfEggsPurchased % 12;
//amount paid for the # of dozens portion.
costForDozens = numberOfDozens * PRICE_PER_DOZEN;
//amount paid for the single eggss portion
costForUnits = numberOfUnitEggs * PRICE_PER_UNIT_EGGS;
//below is the total amount paid in $
totalAmount = costForDozens + costForUnits;
//information displayed in the dialog box upon execution of the program.
JOptionPane.showMessageDialog(null, " You ordered " + howManyEggs + "
eggs. That is " + numberOfDozens + " dozens at $3.25 per dozen and " +
numberOfUnitEggs + " egg(s) at 45.0 cents each for a total of $" +
totalAmount );
}
}
Page 50 Game Question
Write a Java application that displays two dialog boxes in sequence. The first
asks you to think of a number between 1 and 10. The second displays a
randomly generated number; the user can see whether his or her guess was
accurate. (In future chapters you will improve this game so that the user can
enter a guess and the program can determine whether the user was correct. If
you wish, you also can tell the user how
far off the guess was, whether the guess was high or low, and provide a
specific number of repeat attempts.) Save the file as RandomGuess.java.
import javax.swing.JOptionPane;
public class RandomGuess {
public static void main(String [] args) {
String newNumber; //the user guess a number declared as astring variable above
//the system asks you to think of any number from 1 to 9
JOptionPane.showMessageDialog(null,"Think of any number from 1 to 9 ");
//User enters the number into a dialog box
newNumber = JOptionPane.showInputDialog(null, "Enter your Guess number here
");
//the computer displays a randomly generated number
JOptionPane.showMessageDialog(null,"The number guess is " + (1 +
(int)(Math.random() * 10)));
}
}
Book Example on Page 137
import java.util.Scanner;
public class ParadiseInfo2 {
public static void main(String[] args) {
double price;
double discount;
double savings;
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter cutoffprice for discount >> " );
price = keyboard.nextDouble();
System.out.print("Enter discount rate as awhole number >> ");
discount = keyboard.nextDouble();
savings = computeDiscountInfo(price, discount);
displayInfo();
System.out.println("Special this week on any order over " + price);
System.out.println("Discount of " + discount + " percent ");
System.out.println("That's a savings of at least $" + savings);
}
public static void displayInfo() {
System.out.println("Paradise Day Spa wants to pamper you,");
System.out.println("We will make you look good.");
}
public static double computeDiscountInfo(double pr, double dscnt) {
double savings;
savings = pr * dscnt/100;
return savings;
}
}
Below is the output generated when this class is executed in NetBeans7
//this creates a class to store information about services offered at Paradise
Spa
public class SpaService {
// two private data fields that will hold data about spa service
private String serviceDescription;
private double price;
//Within the class’s curly braces and after the field declarations, enter the
//following two methods that set the field values. The setServiceDescription()
//method accepts a String parameter and assigns it to the serviceDescription
//field for each object that eventually will be instantiated. Similarly, the setPrice()
method accepts a double parameter and assigns it to the price field. Note that neither
of these methods is static.
public void setServiceDescription(String service){
serviceDescription = service;
}
public void setPrice(double pr) {
price = pr;
}
//Next, add two methods that retrieve the field values as follows:
public String getServiceDescription() {
return serviceDescription;
}
public double getPrice() {
return price;
}
}
//Save the file as SpaService.java, compile it, and then correct any syntax
//errors. Remember, you cannot run this file as a program because it does not
//contain a public static main() method. After you read the next section, you
//will use this class to create objects.
This class runs along with the previous class to give the output below when ran
on NetBeans8.1
//Open a new file in your text editor, and type the import statement needed for
//an interactive program that accepts user keyboard input:
import java.util.Scanner;
//Create the shell for a class named CreateSpaServices:
public class CreateSpaServices {
//Between the curly braces of the CreateSpaServices class, create the shell
//for a main() method for the application:
public static void main(String[] args) {
//Within the main() method, declare variables to hold a service description and
//price that a user can enter from the keyboard:
String service;
double price;
//Next, declare three objects. Two are SpaService objects that use the class you
created in the prior set of “You Do It” steps. The third object uses the built-in Java
Scanner class. Both classes use the new operator to allocate memory for their
objects, and both call a constructor that has the same name as the class. The
difference is that the Scanner constructor requires an argument (System.in), but the
SpaService class does not.
SpaService firstService = new SpaService();
SpaService secondService = new SpaService();
Scanner keyboard = new Scanner(System.in);
//In the next statements, you prompt the user for a service, accept it from the
//keyboard, prompt the user for a price, and accept it from the keyboard.
System.out.print("Enter service >> ");
service = keyboard.nextLine();
System.out.print("Enter price >> ");
price = keyboard.nextDouble();
//Recall that the setServiceDescription() method in the SpaService class is
//nonstatic, meaning it is used with an object, and that it requires a String
//argument. Write the statement that sends the service the user entered to the
//setServiceDescription() method for the firstService object:
firstService.setServiceDescription(service);
//Similarly, send the price the user entered to the setPrice() method for the
//firstService object. Recall that this method is nonstatic and requires a double
//argument.
firstService.setPrice(price);
//Make a call to the nextLine() method to remove the Enter key that remains in
//the input buffer after the last numeric entry. Then repeat the prompts, and
//accept data for the second SpaService object.
keyboard.nextLine();
System.out.print("Enter service >> ");
facialservice = keyboard.nextLine();
System.out.print("Enter price >> ");
price = keyboard.nextDouble();
secondService.setServiceDescription(service);
secondService.setPrice(price);
//Display the details for the firstService object.
System.out.println("First service details:");
System.out.println(firstService.getServiceDescription() + " "
+ "$" + firstService.getPrice());
//Display the details for the secondService object.
System.out.println("Second service details:");
System.out.println(secondService.getServiceDescription() + " $" +
secondService.getPrice());
//Save the file as CreateSpaServices.java. Compile and execute the program.
//Figure 3-31 shows a typical execution. Make sure you understand how the user’s
//entered values are assigned to and retrieved from the two SpaService objects.
}
}
}
}
CHAPTER 3 QUESTIONS
3a. Create an application named ArithmeticMethods whose main() method
holds two integer variables. Assign values to the variables. In turn, pass each
value to methods named displayNumberPlus10(), displayNumberPlus100(),
and displayNumberPlus1000(). Create each method to perform the task its
name implies. Save the application as ArithmeticMethods.java.
C:UsersChristopherDocumentsNetBeansProjectsJRVampedsrcArithmeticMethods.java
// This class receives two numbers and then display the result
// of adding 10, 100 and 1000 to them in turn.
public class ArithmeticMethods
{
public static void main(String[] args)
{
// Two integers 13 and 31 are declared. These are passed as arguments
// to each of th three methods that follows
int firstNumber = 13;
int secondNumber = 31;
System.out.println("The number pairs " + firstNumber + " and " + secondNumber);
// The main class above implements each of the three arithmetic methods below
// in turn. Note that each of these classes are placed outside the main class
above.
displayNumberPlus10(firstNumber, secondNumber);
displayNumberPlus100(firstNumber, secondNumber);
displayNumberPlus1000(firstNumber, secondNumber);
}
// The first method, displayNumberPlus10
public static void displayNumberPlus10(int firstNumber, int secondNumber)
{
int firstNumberPlus10, secondNumberPlus10;
firstNumberPlus10 = firstNumber + 10;
secondNumberPlus10 = secondNumber + 10;
System.out.println("displayNumberPlus10 is: " + firstNumberPlus10 + " and " +
secondNumberPlus10);
}
// The second method, displayNumberPlus100
public static void displayNumberPlus100(int firstNumber, int secondNumber)
{
int firstNumberPlus100, secondNumberPlus100;
firstNumberPlus100 = firstNumber + 100;
secondNumberPlus100 = secondNumber + 100;
System.out.println("displayNumberPlus10 is: " + firstNumberPlus100 + " and " +
secondNumberPlus100);
}
// The third method, displayNumberPlus1000
public static void displayNumberPlus1000(int firstNumber, int secondNumber)
{
int firstNumberPlus1000, secondNumberPlus1000;
firstNumberPlus1000 = firstNumber + 1000;
secondNumberPlus1000 = secondNumber + 1000;
System.out.println("displayNumberPlus10 is: " + firstNumberPlus1000 + " and " +
secondNumberPlus1000);
}
}
3b. Modify the ArithmeticMethods class to accept the values of the two integers from
a user at the keyboard. Save the file as ArithmeticMethods2.java.
C:UsersChristopherDocumentsNetBeansProjectsJRVampedsrcArithmeticMethods2.java
/*
* The previous problem is modified so that user can enter any two numbers
*/
// Add the import statement for user keyboard entry
import java.util.Scanner;
// The main class receives two numbers and display the result of adding
// 10, 100 and 1000 to them in turn
public class ArithmeticMethods2
{
public static void main(String[] args)
{
// Two integers are declared
int firstNumber, secondNumber;
//For user keyboard entry
Scanner keyboard = new Scanner(System.in);
// input firstNumber
System.out.println("Enter the first number:>> ");
firstNumber = keyboard.nextInt();
// input secondNumber
System.out.println("Enter the second number:>> ");
secondNumber = keyboard.nextInt();
// Display the numbers
System.out.println("First number is: " + firstNumber + "; Second number is: " +
secondNumber);
// The following 3 methods are implemented by the main class for each of
// the subsequent additions
displayNumberPlus10(firstNumber, secondNumber);
displayNumberPlus100(firstNumber, secondNumber);
displayNumberPlus1000(firstNumber, secondNumber);
}
// This is the first method
public static void displayNumberPlus10(int firstNumber, int secondNumber)
{
int firstNumberPlus10, secondNumberPlus10;
firstNumberPlus10 = firstNumber + 10;
secondNumberPlus10 = secondNumber +10;
System.out.println("displayNumberPlus10 is: " + firstNumberPlus10 + " and " +
secondNumberPlus10);
}
// This is the second method
public static void displayNumberPlus100(int firstNumber, int secondNumber)
{
int firstNumberPlus100, secondNumberPlus100;
firstNumberPlus100 = firstNumber + 100;
secondNumberPlus100 = secondNumber +100;
System.out.println("displayNumberPlus100 is: " + firstNumberPlus100 + " and " +
secondNumberPlus100);
}
// This is the third method
public static void displayNumberPlus1000(int firstNumber, int secondNumber)
{
int firstNumberPlus1000, secondNumberPlus1000;
firstNumberPlus1000 = firstNumber + 1000;
secondNumberPlus1000 = secondNumber +1000;
System.out.println("displayNumberPlus1000 is: " + firstNumberPlus1000 + " and " +
secondNumberPlus1000);
}
}
Modify the ArithmeticMethods class to accept the values of the two integers from
a user at the keyboard. Save the file as ArithmeticMethodsInteractive.java.
C:UsersChristopherDocumentsNetBeansProjectsJRVampedsrcArithmeticMethodsInteractive.java
import javax.swing.JOptionPane; // For dialog box input and output
// This class receives two integer numbers and display the result of
// adding 10, 100 and 1000 to them in that order
public class ArithmeticMethodsInteractive
{
public static void main(String[] args)
{
int firstNumber, secondNumber;
String numberOne, numberTwo; // needed to enter numbers as Strings
// in the JOptionPane
numberOne = JOptionPane.showInputDialog(null, "First Number",
"Enter the first number", JOptionPane.INFORMATION_MESSAGE);
// the number entered into the dialog box above is a String. It needs to be
// parsed into an integer before arithmetic operations can be done on it.
firstNumber = Integer.parseInt(numberOne);
numberTwo = JOptionPane.showInputDialog(null, "Second Number",
"Enter the Second number", JOptionPane.INFORMATION_MESSAGE);
secondNumber = Integer.parseInt(numberTwo);
// The main() class above implements each of the 3 methods below.
displayNumberPlus10(firstNumber, secondNumber);
displayNumberPlus100(firstNumber, secondNumber);
displayNumberPlus1000(firstNumber, secondNumber);
}
// This is the first method
public static void displayNumberPlus10(int firstNumber, int secondNumber)
{
int firstNumberPlus10, secondNumberPlus10;
firstNumberPlus10 = firstNumber + 10;
secondNumberPlus10 = secondNumber +10;
// The results of the above addition are displayed in a dialog box
JOptionPane.showMessageDialog(null, "firstNumberPlus10 is: " +
firstNumberPlus10 + " and " + secondNumberPlus10);
}
// This is the second method
public static void displayNumberPlus100(int firstNumber, int secondNumber)
{
int firstNumberPlus100, secondNumberPlus100;
firstNumberPlus100 = firstNumber + 100;
secondNumberPlus100 = secondNumber +100;
// The results of the above addition are displayed in a dialog box
JOptionPane.showMessageDialog(null, "firstNumberPlus10 is: " +
firstNumberPlus100 + " and " + secondNumberPlus100);
}
// This is the third method
public static void displayNumberPlus1000(int firstNumber, int secondNumber)
{
int firstNumberPlus1000, secondNumberPlus1000;
firstNumberPlus1000 = firstNumber + 1000;
secondNumberPlus1000 = secondNumber +1000;
// The results of the above addition are displayed in a dialog box
JOptionPane.showMessageDialog(null, "firstNumberPlus10 is: " +
firstNumberPlus1000 + " and " + secondNumberPlus1000);
}
}
4. a. Create an application named Percentages whose main() method holds
two double variables. Assign values to the variables. Pass both variables to a
method named computePercent() that displays the two values and the value of
the first number as a percentage of the second one. For example, if the
numbers are 2.0 and 5.0, the method should display a statement similar to
“2.0 is 40% of 5.0.” Then call themethod a second time, passing the values in
reverse order. Save the application as Percentages.java.
C:UsersChristopherDocumentsNetBeansProjectsJRVampedsrcPercentage.java
public class Percentage
{
public static void main(String[] args)
{
double numFirst = 2.0;
double numSecond = 5.0;
computePercent(numFirst, numSecond); // This method compute percentages
}
public static void computePercent(double numFirst, double numSecond)
{
double firstPercentSecond; // First number as a percentage of second
double secondPercentFirst; // Second number as a percentage of first
firstPercentSecond = 100 * numFirst/numSecond;
secondPercentFirst = 100 * numSecond/numFirst;
// Display the results
System.out.println(numFirst + " is " + firstPercentSecond + "% of " + numSecond);
System.out.println(numSecond + " is " + secondPercentFirst + "% of " +
numFirst);
}
}
b. Modify the Percentages class to accept the values of the two doubles from a user
at the keyboard. Save the file as Percentages2.java.
C:UsersChristopherDocumentsNetBeansProjectsJRVampedsrcPercentages2.ja
va
/*
This application expresses the first number entered as a percentage of the
second and also the second number entered as a percentage of the first.
*/
import java.util.Scanner;
public class Percentages2
{
public static void main(String[] args)
{
double numFirst, numSecond;
Scanner keyboard = new Scanner(System.in);
// Input the first number
System.out.println("Enter the first number: ");
numFirst = keyboard.nextInt();
// Input the second number
System.out.println("Enter the second number: ");
numSecond = keyboard.nextInt();
// the main method now calls the method that compute percentages
computePercent(numFirst, numSecond);
}
// the numbers entered from the above are now passed
// to the computePercent() method below
public static void computePercent(double numFirst, double numSecond)
{
double firstPercentSecond, secondPercentFirst; // % values to be computed
firstPercentSecond = 100 * numFirst/numSecond;
secondPercentFirst = 100 * numSecond/numFirst;
// Display the results of the above calculation
System.out.println(numFirst + " is " + firstPercentSecond + "% of " + numSecond);
System.out.println(numSecond + " is " + secondPercentFirst + "% of " +
numFirst);
}
}
Java   small steps - 2019
INTERACTIVE VERSION (PercentageInteractive.java)
C:UsersChristopherDocumentsNetBeansProjectsJRVampedsrcPercentageInteractive.va
// Interactive version of previous problem
import javax.swing.JOptionPane; // Needed for dialog box input and output
public class PercentageInteractive
{
public static void main(String[] args)
{
double numFirst, numSecond; // Declare two double variables
String numberOne, numberTwo; // numbers as Strings into dialog box
// input first number
numberOne = JOptionPane.showInputDialog(null, "First Number",
"Enter the first number", JOptionPane.INFORMATION_MESSAGE);
numFirst = Integer.parseInt(numberOne);
// input second number
numberTwo = JOptionPane.showInputDialog(null, "Second Number",
"Enter the second number", JOptionPane.INFORMATION_MESSAGE);
numSecond = Integer.parseInt(numberTwo);
// The main() class calls the computePercent() method
computePercent(numFirst, numSecond);
}
// the numbers entered above are now parsed to the computePercent() method
public static void computePercent(double numFirst, double numSecond)
{
double firstPercentSecond, secondPercentFirst;
firstPercentSecond = 100 * numFirst/numSecond;
secondPercentFirst = 100 * numSecond/numFirst;
// the results of the computePercent method are displayed in the next
// two message boxes
JOptionPane.showMessageDialog(null, numFirst + " is " + firstPercentSecond
+ "% of " + numSecond);
JOptionPane.showMessageDialog(null, numSecond + " is " + secondPercentFirst
+ "% of " + numFirst);
}
}
There are 2.54 centimeters in an inch, and there are 3.7854 liters in a U.S.
gallon.
6. Create a class named MetricConversion. Its main() method accepts an
integer value from a user at the keyboard, and in turn passes the
entered value to two methods. One converts the value from inches to
centimeters and the other converts the same value from gallons to
liters. Each method displays the results with appropriate explanation.
Save the application as MetricConversion.java.
C:UsersChristopherDocumentsNetBeansProjectsJRVampedsrcMetricConversion.java
import java.util.Scanner;
public class MetricConversion
{
public static void main(String[] args)
{
// The value to convert is entered as a double
double valueToConvert;
Scanner keyboard = new Scanner(System.in);
// This value is entered fro the keyboard
System.out.print("Enter the value to convert:>> ");
valueToConvert = keyboard.nextDouble();
// Next, the main method invoke the two methods that
// carrry out the conversion
inchesToCm(valueToConvert);
gallonsToLitres(valueToConvert);
}
// The inchesToCm() method
public static void inchesToCm(double valueToConvert)
{
final double INCHES_TO_CM = 2.54;
double lengthInCm = valueToConvert * INCHES_TO_CM;
System.out.println(valueToConvert + " inches = " + lengthInCm + " cm");
}
// The gallonsToLitres() method
public static void gallonsToLitres(double valueToConvert)
{
final double GALLONS_TO_LITRES = 3.7854;
double volInLitres = valueToConvert * GALLONS_TO_LITRES;
System.out.println(valueToConvert + " gallons = " + volInLitres + " litres");
}
}
Q7. Assume that a gallon of paint covers about 350 square feet of wall space. Create
an application with a main() method that prompts the user for the length, width, and
height of a rectangular room. Pass these three values to a method that does the
following:
 Calculates the wall area for a room
 Passes the calculated wall area to another method that calculates and returns
the number of gallons of paint needed
 Displays the number of gallons needed
 Computes the price based on a paint price of $32 per gallon, assuming that
the painter can buy any fraction of a gallon of paint at the same price as a
whole gallon
 Returns the price to the main() method
The main() method displays the final price. For example, the cost to paint a 15- by-20-
foot room with 10-foot ceilings is $64. Save the application as PaintCalculator.java.
C:UsersChristopherDocumentsNetBeansProjectsJRVampedsrcPaintCalculator.java
/*
NOTE: TOTAL WALL AREA OF A ROOM IS
2*(LENGTH * WIDTH + LENGTH * HEIGHT + WIDTH * HEIGHT)
NOTE THAT THE FLOOR AND THE CEILING NEED NO PAINTING
THEREFORE, TOTAL WALL AREA TO BE PAINTED IS
2 * (LENGTH * WIDTH + WIDTH * HEIGHT)
*/
import java.util.Scanner;
public class PaintCalculator
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.print("Enter the length in feet:>> ");
double length = input.nextDouble();
System.out.print("Enter the width in feet:>> ");
double width = input.nextDouble();
System.out.print("Enter the height in feet:>> ");
double height = input.nextDouble();
System.out.println();
// Declare variables associated with the totalWallArea computation
double wallsArea; // Total Wall Area
double volGallons; // Voulme of paint needed
double costs; // Cost of painting the walls
// Method that computes total wall area
wallsArea = computeTotalWallArea(length, width, height);
final double SQFT_PER_GALLON = 350;
volGallons = wallsArea/SQFT_PER_GALLON;
final double COST_PER_GALLON = 32; // Cost per gallon
double cost; // Cost to pain the walls.
cost = volGallons * COST_PER_GALLON;
System.out.println("Gallons needed is:>> " + volGallons + " gals ");
System.out.println("Total cost for painting wall of " + length + " ft by "
+ width + " ft by " + height + " ft is:>> $" + cost);
}
public static double computeTotalWallArea(double length, double width, double
height)
{
double totalWallArea;
totalWallArea = 2 * (length * height + width * height);
System.out.println("The total wall area is: " + totalWallArea + " sq.ft");
return totalWallArea;
}
}
8. The Harrison Group Life Insurance company computes annual policy
premiums based on the age the customer turns in the current calendar year.
The premium is computed by taking the decade of the customer’s age, adding
15 to it, and multiplying by 20. For example, a 34-year-old would pay $360,
which is calculated by adding the decades (3) to 15, and then multiplying by
20. Write an application that prompts a user for the current year and a birth
year. Pass both to a method that calculates and returns the premium amount,
and then display the returned amount.
Save the application as Insurance.java.
C:UsersChristopherDocumentsNetBeansProjectsJRVampedsrcInsurance.java
/*
* IN THIS APP, THE OLDER YOU ARE, THE MORE.
* YOU PAY FOR INSURANCE
*/
import java.util.Scanner;
public class Insurance
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.print("Enter the year you were born:>> ");
int birthYear = input.nextInt();
System.out.print("Enter the current year:>> ");
int currentYear = input.nextInt();
//Call the method that computes the applicable insurance premium
computePremiumAmount(birthYear, currentYear);
}
public static int computePremiumAmount(int birthYear, int currentYear)
{
int premiumAmount, decadeYears;
final int DECADE_FACTOR = 10;
final int YEAR_ADD_ON = 15;
final int MULTIPLIER = 20;
decadeYears = (currentYear - birthYear) / DECADE_FACTOR;
premiumAmount = (decadeYears + YEAR_ADD_ON) * MULTIPLIER;
System.out.println("Total premium is:>> $" + premiumAmount);
return premiumAmount;
}
}
9. Write an application that calculates and displays the weekly salary for an
employee. The main() method prompts the user for an hourly pay rate, regular
hours, and overtime hours. Create a separate method to calculate overtime
pay, which is regular hours times the pay rate plus overtime hours times 1.5
times the pay rate; return the result to the main() method to be displayed.
Save the program as Salary.java.
C:UsersChristopherDocumentsNetBeansProjectsJRVampedsrcSalary.java
import java.util.Scanner;
public class Salary
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.print("Enter the # of hours of regular work:>> ");
double regularHours = input.nextDouble();
System.out.print("Enter the regular hourly rate:>> ");
double regularRate = input.nextDouble();
System.out.print("Enter the # of hours of overtime work:>> ");
double overtimeHours = input.nextDouble();
// Call the method that computes the total pay below
totalPay(regularHours, regularRate, overtimeHours);
}
public static double totalPay(double regularHours, double regularRate,
double overtimeHours)
{
double totalPay;
totalPay = regularHours * regularRate + overtimeHours * regularRate * 1.5;
System.out.println("Total pay is:>> $" + totalPay);
return totalPay;
}
}
10. Write an application that calculates and displays the amount of money a
user would have if his or her money could be invested at 5 percent interest
for one year. Create a method that prompts the user for the starting value of
the investment and returns it to the calling program. Call a separate method to
do the calculation, and return the result to be displayed. Save the program as
Interest.java.
C:UsersChristopherDocumentsNetBeansProjectsJRVampedsrcInterest.java
import java.util.Scanner;
public class Interest
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.print("Enter the starting amount:>> ");
double principal = input.nextDouble();
System.out.print("Enter the interest rate:>> ");
double rate = input.nextDouble();
System.out.print("Enter the number of years:>> ");
int time = input.nextInt();
// The main() method now calls the method that calculates
// the amount
amount(principal, rate, time);
}
public static double amount(double principal, double rate, int time)
{
double amount = principal * (1 + rate * time/100);
System.out.println("The amount is:>> $" + amount);
return amount;
}
}
11. a. Create a class named Sandwich. Data fields include a String for the main
ingredient (such as “tuna”), a String for bread type (such as “wheat”), and a double for
price (such as 4.99). Include methods to get and set values for each of these fields.
Save the class as Sandwich.java. b. Create an application named TestSandwich that
instantiates one Sandwich object and demonstrates the use of the set and get
methods. Save this application as TestSandwich.java.
/*Note that this class, Sandwich, cannot run on its own. It doesn't have a main
method It must be in the same folder as the TestSandwich folder for the latter to run */
C:UsersChristopherDocumentsNetBeansProjectsJRVampedsrcSandwich.java
public class Sandwich
{
//Insert three private data fields
private double price;
private String mainIngredient;
private String breadType;
/**
* The following three methods set the fields values
* The first method is for the mainIngredient
* The second method is for the breadType
* The third method is for the price
*/
// Mutator methods
public void setMainIngredient(String ingredient)
{
mainIngredient = ingredient;
}
public void setBreadType(String type)
{
breadType = type;
}
public void setPrice(double pr)
{
price = pr;
}
/**
* The following three methods get the fields values
* The first method is for the mainIngredient
* The second method is for the breadType
* The third method is for the price
*/
// Accessor methods
public String getMainIngredient()
{
return mainIngredient;
}
public String getBreadType()
{
return breadType;
}
public double getPrice()
{
return price;
}
}
/*Note that this class, TestSandwich, must be in the same folder as the
Sandwhich
class for it to run*/
C:UsersChristopherDocumentsNetBeansProjectsJRVampedsrcTestSandwich.java
import java.util.Scanner;
public class TestSandwich
{
public static void main(String[] args)
{
// Declare variables to hold the sandwich type, bread type
// the price that customers pay per sandwich
String ingredient;
String type;
double price;
/**
* Next, create three objects that uses the previously created Sandwich
class. The three objects are for the sandwich type and the built in Java class. All the
three classes use the new operator to allocate memory for their new objects. Each of
the new classes call a constructor that has the same name as the class Sandwich.
The difference is that the Scanner class requires an argument (System.in) but the
Sandwich class does not.
*/
Sandwich sandwichType = new Sandwich();
Sandwich breadType = new Sandwich();
Scanner keyboard = new Scanner(System.in);
/**
* The next statements prompts the user to enter the type of sandwich,
bread type and
* price in that order.
*/
System.out.print("Enter the type of sandwich:>> ");
ingredient = keyboard.nextLine();
System.out.print("Enter the type of bread used:>> ");
type = keyboard.nextLine();
System.out.print("Enter the price:>> ");
price = keyboard.nextDouble();
/**
* The following three statements send the order the user placed to each of
the the three
* corresponding methods in Sandwich class.
*/
sandwichType.setMainIngredient(ingredient);
sandwichType.setBreadType(type);
sandwichType.setPrice(price);
// Final output
System.out.println("");
System.out.println("Here is the summary of your order");
System.out.println("--------------------------------------------");
System.out.println("Sandwich type: >> " + sandwichType.getMainIngredient());
System.out.println("Bread type: >>" + sandwichType.getBreadType());
System.out.println("For a total price of:>> $" + sandwichType.getPrice());
}
}
12. a. Create a class named Student. A Student has fields for an ID number, number
of credit hours earned, and number of points earned. (For example, many schools
compute grade point averages based on a scale of 4, so a three-credit-hour class in
which a student earns an A is worth 12 points.) Include methods to assign values to
all fields. A Student also has a field for grade point average. Include a method to
compute the grade point average field by dividing points by credit hours earned. Write
methods to display the values in each Student field. Save this class as Student.java.
b. Write a class named ShowStudent that instantiates a Student object from the class
you created and assign values to its fields. Compute the Student grade point average,
and then display all the values associated with the Student. Save the application as
ShowStudent.java.
c. Create a constructor for the Student class you created. The constructor should
initialize each Student’s ID number to 9999, his or her points earned to 12, and credit
hours to 3 (resulting in a grade point average of 4.0). Write a program that
demonstrates that the constructor works by instantiating an object and displaying the
initial values. Save the application as ShowStudent2.java.
/*The Student class doesn't have a main method. It must be in the
same folder as the ShowStudent class for the latter to run */
C:UsersChristopherDocumentsNetBeansProjectsJRVampedsrcStudent.java
public class Student
{
// Insert three private data fields
private int studentIdNumber;
private double creditHoursEarned;
private double creditPointsEarned;
/**
* Mutatator methods for setting field values
* student's ID number
* credit hours earned
* credit points earned.
*/
public void setStudentNumber(int idNumber)
{
studentIdNumber = idNumber;
}
public void setCreditHoursEarned(double creditHours)
{
creditHoursEarned = creditHours;
}
public void setCreditPointsEarned(double points)
{
creditPointsEarned = points;
}
/**
* Accessor methods for getting field values:
* student's ID number
* credit hours earned
* credit points earned.
*/
public int getStudentNumber()
{
return studentIdNumber;
}
public double getCreditHoursEarned()
{
return creditHoursEarned;
}
public double getCreditPointsEarned()
{
return creditPointsEarned;
}
// Default constructor takes no parameters, it has default values
public Student()
{
studentIdNumber = 9999;
creditPointsEarned = 12;
creditHoursEarned = 3;
}
}
C:UsersChristopherDocumentsNetBeansProjectsJRVampedsrcShowStudent.java
import java.util.Scanner;
public class ShowStudent
{
public static void main(String[] args)
{
// Declare variables for the ID#, creedit hours earned, credit points
// earned, grade point average and the Scanner object for user input
int idNumber;
double creditHoursEarned;
double creditPointsEarned;
double gradePointAverage;
Scanner keyboard = new Scanner(System.in);
/**
* Create objects that use the previously created Student class.
* The object is for a new student (firstStudent). The new operator is used
* to allocate memory for the Student object. Both call constructors that has
* the same name as the class, Student.
*/
Student firstStudent = new Student();
/**
* The following lines prompts the user for the student's ID#,
* credit hours earned and total points earned.
*/
System.out.print("Enter student's ID #:>>> ");
idNumber = keyboard.nextInt();
System.out.print("Enter the total credit hours earned:>> ");
creditHoursEarned = keyboard.nextInt();
System.out.print("Enter total points earned:>> ");
creditPointsEarned = keyboard.nextInt();
// Calculating the grade point average
gradePointAverage = creditPointsEarned / creditHoursEarned;
/**
* The following three methods send the firstStudent data to the
* methods created in Student class. The fourth line calls on the
* method for calculating gradePointAverage.
*/
firstStudent.setStudentNumber(idNumber);
firstStudent.getCreditPointsEarned();
firstStudent.setCreditPointsEarned(creditPointsEarned);
gradePointAverage(creditHoursEarned, creditPointsEarned);
// Program execution printout
System.out.println("");
System.out.println("Below are student with ID#: " + firstStudent.getStudentNumber()
+
" Score Details");
System.out.println("Total credit hours earned:>> " +
firstStudent.getCreditHoursEarned());
System.out.println("Total credit points earned:>> " +
firstStudent.getCreditPointsEarned());
System.out.println("CGPA:>> " + gradePointAverage);
//Demonstrating default constructor
Student defaultStudent;
defaultStudent = new Student();
{
int idNum = defaultStudent.getStudentNumber();
double creditHours = defaultStudent.getCreditHoursEarned();
double creditPoints = defaultStudent.getCreditPointsEarned();
//double creditAverage = defaultStudent.getCreditPointsEarned();
gradePointAverage = creditPoints / creditHours; //(creditHours, creditPoints);
System.out.println("++++++++++++++++");
System.out.println("Default Student ID# is:>> " + idNum);
System.out.println("Default credit hours earned:>> " + creditHours);
System.out.println("Default credit points earned:>> " + creditPoints);
System.out.println("Default cumulative grade poit average:>> " +
gradePointAverage);
}
}
// Method for calculating grade point average.
public static double gradePointAverage(double creditHoursEarned, double
creditPointsEarned)
{
double gradePointAverage;
gradePointAverage = creditPointsEarned / creditHoursEarned;
//System.out.print(gradePointAverage);
return gradePointAverage;
}
}
Question 13 Page 174 (Note: Answers not exactly like it was in the text)
a. Create a class named BankAccount with fields that hold an account
number, the owner’s name, and the account balance. Include a constructor
that initializes each field to appropriate default values. Also include
methods to get and set each of the fields. Include a method named
deductMonthlyFee() that reduces the balance by $4.00. Include a static
method named explainAccountPolicy() that explains that the $4 service fee
will be deducted each month. Save the class as BankAccount.java.
b. Create a class named TestBankAccount whose main() method declares
four BankAccount objects. Call a getData() method three times. Within the
method, prompt a user for values for each field for a BankAccount, and
return a BankAccount object to the main() method where it is assigned to
one of main()’s BankAccount objects. Do not prompt the user for values for
the fourth BankAccount object, but let it continue to hold the default values.
Then, in main(), pass each BankAccount object in turn to a showValues()
method that displays the data, calls the method that deducts the monthly
fee, and displays the balance again. The showValues() method also calls
the method that explains the deduction policy. Save the application as
TestBankAccount.java.
13A
C:UsersChristopherDocumentsNetBeansProjectsJRVampedsrcNBankAccount.j
ava
public class NBankAccount
{
// Data field variable names
private int accountNum;
private String accountName;
private double accountBalance;
// The account method that receive parameters in the constructors
public NBankAccount(int acctNum, String name, double balance)
{
this.accountNum = acctNum;
this.accountName = name;
this.accountBalance = balance;
}
// The default account method with no parameter in the constructors
public NBankAccount()
{
accountNum = 123456;
accountName = "Willy Akinlade";
accountBalance = 00.00;
}
// The following are the set methods
public void setAccountNum(int acctNum)
{
accountNum = acctNum;
}
public void setAccountName(String ownersName)
{
accountName = ownersName;
}
public void setAccountBalance(double acctBalance)
{
accountBalance = acctBalance;
}
// The following are the get methods
public int getAccountNum()
{
return accountNum;
}
public String getAccountName()
{
return accountName;
}
public double getAccountBalance()
{
return accountBalance;
}
}
13BC:UsersChristopherDocumentsNetBeansProjectsJRVampedsrcTestNBankAccount.java
import java.util.Scanner;
public class TestNBankAccount
{
public static void main(String[] args)
{
// first account parameters values
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter firstAccount #:>> ");
int accountNum = keyboard.nextInt();
System.out.print("Enter firstAccount owner:>> ");
String accountName = keyboard.next();
System.out.print("Enter firstAccount balance:>> $");
double accountBalance = keyboard.nextDouble();
System.out.println("");
// Creating firstAccount object
NBankAccount firstAccount;
firstAccount = new NBankAccount(accountNum, accountName, accountBalance);
{
int accountNumber = firstAccount.getAccountNum();
String acctName = firstAccount.getAccountName();
double acctBalance = firstAccount.getAccountBalance();
double newBalance = acctBalance - 4;
// Screen output for firstAccount
System.out.println("firstAccount #:>> " + accountNumber);
System.out.println("firstAccount owner:>> " + acctName);
System.out.println("firstAccount balance before deduction:>> $" + acctBalance);
System.out.println("firstAccount balance after deduction:>> $" + newBalance);
System.out.println(" ");
System.out.println("NOTE: A monthly fe of $4.00 is deducted as service fees.");
System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~");
}
System.out.print("");
// Enter the second account parameter values
System.out.print("Enter secondAccount #:>> ");
int secAccountNum = keyboard.nextInt();
System.out.print("Enter secondAccount owner:>> ");
String secAccountName = keyboard.next();
System.out.print("Enter secondAccount balance:>> $");
double secAccountBalance = keyboard.nextDouble();
System.out.println(" ");
// Creating secondAccount object
NBankAccount secondAccount;
secondAccount = new NBankAccount(secAccountNum, secAccountName,
secAccountBalance);
{
int accountNumber = secondAccount.getAccountNum();
String acctName = secondAccount.getAccountName();
double acctBalance = secondAccount.getAccountBalance();
double newBalance = acctBalance - 4;
// Screen output for secondAccount
System.out.println("secondAccount #:>> " + accountNumber);
System.out.println("secondAccount owner:>> " + acctName);
System.out.println("secondAccount balance before defuction:>> $" +
acctBalance);
System.out.println("secondAccount balance after desduction:>> $" +
newBalance);
System.out.println("NOTE: A monthly fe of $4.00 is deducted as service fees.");
System.out.println(" ");
System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~");
}
// This is the default account, it returns default values
NBankAccount thirdAccount;
thirdAccount = new NBankAccount();
{
int accountNumber = thirdAccount.getAccountNum();
String acctName = thirdAccount.getAccountName();
double acctBalance = thirdAccount.getAccountBalance();
System.out.println(" ");
System.out.println("Default number:>>" + accountNumber);
System.out.println("Default owner:>>" + acctName);
System.out.println("Default account balance:>> $" + acctBalance);
}
}
}
Question 14 page 174,
14. a. Create a class named Painting that contains fields for a painting’s title,
artist, medium (such as water color), price, and gallery commission. Create a
constructor that initializes each field to an appropriate default value, and
create instance methods that get and set the fields for title, artist, medium, and
price. The gallery commission field cannot be set from outside the class; it is
computed as 20 percent of the price each time the price is set. Save the class
as
Painting.java.
b. Create a class named TestPainting whose main() method declares three
Painting items. Create a method that prompts the user for and accepts values
for two of the Painting objects, and leave the third with the default values
supplied by the constructor. Then display each completed object. Finally,
display a message that explains the gallery commission rate. Save the
application as TestPainting.java.
Painting Class
C:UsersChristopherDocumentsNetBeansProjectsJRVampedsrcPainting.java
public class Painting
{
// Private data fields
private String title;
private String artist;
private String medium;
private double price;
private double commission;
// Constructor that receive parameters
public Painting(String pTitle, String pArtist, String pMedium, double pCost)
{
this.title = pTitle;
this.artist = pArtist;
this.medium = pMedium;
this.price = pCost;
}
// Default constructor takes no parameters, it has default values
public Painting()
{
title = "AAAAA";
artist = "XXXXX";
medium = "ZZZZZ";
price = 25000.00;
}
// Accessor and mutator methods
public String getTitle()
{
return title;
}
public void setTitle(String description)
{
title = description;
}
public String getArtist()
{
return artist;
}
public void setArtist(String theArtist)
{
artist = theArtist;
}
public String getMedium()
{
return medium;
}
public void setMedium(String media)
{
medium = media;
}
public double getPrice()
{
return price;
}
public void setPrice(double cost)
{
price = cost;
}
public double getCommission()
{
double commission;
commission = 0.2 * this.price;
return commission;
}
}
TestPainting main () class
C:UsersChristopherDocumentsNetBeansProjectsJRVampedsrcTestPainting.java
import java.util.Scanner;
public class TestPainting
{
public static void main(String[] args)
{
// Create Scanner object for user input of the variables declared above
Scanner keyboard = new Scanner(System.in);
// Declare the variables that the user will enter into the created object
String title;
String artist;
String medium;
double price;
System.out.print("Enter painting description:>> ");
title = keyboard.next();
System.out.print("Enter the name of artist:>> ");
artist = keyboard.next();
System.out.print("Enter the medium used:>> ");
medium = keyboard.next();
System.out.print("Enter the painting price:>> $");
price = keyboard.nextDouble();
// Creating first Painting object
Painting firstArtWork = new Painting(title, artist, medium, price);
{
String descr = firstArtWork.getTitle();
String author = firstArtWork.getArtist();
String material = firstArtWork.getMedium();
double cost = firstArtWork.getPrice();
double commission = firstArtWork.getCommission();
System.out.println(" ");
System.out.println("Painting title is:>> " + descr);
System.out.println("Artist name is:>> " + author);
System.out.println("The material used:>> " + material);
System.out.println("Cost for the painting:>> $" + cost + "n");
System.out.println("Commission for the painting:>> $" + commission );
System.out.println("NOTE: A 20% sales commission charges apply");
System.out.println("~~~~~~~~~~~~~~");
}
// This is the default account, it returns default values
Painting defaultArtWork;
defaultArtWork = new Painting();
{
String description = defaultArtWork.getTitle();
String painter = defaultArtWork.getArtist();
String materl = defaultArtWork.getMedium();
double pricing = defaultArtWork.getPrice();
double commission = defaultArtWork.getCommission();
System.out.println(" ");
System.out.println("Default painting is:>>" + description);
System.out.println("Default artist is:>>" + painter);
System.out.println("Default medium is:>>" + materl);
System.out.println("Default price:>> $" + pricing +"n");
System.out.println("Commission for the painting:>> $" + commission);
System.out.println("NOTE: A 20% sales commission charges apply");
}
}}
DEMONSTRATING Overloading
C:UsersChristopherDocumentsNetBeansProjectsJDMay2018srcDemoOverload.java
// This class demonstrates Overloading - Page 197 Joyce Farrel 8th Ed
public class DemoOverload
{
public static void main(String[] args)
{
int month = 6, day = 24, year = 2015;
displayDate(month);
displayDate(month, day);
displayDate(month, day, year);
}
// Overloaded method display the month
public static void displayDate(int mm)
{
System.out.println("Event date " + mm + "/1/2014");
}
// Overloaded method display the month and day
public static void displayDate(int mm, int dd)
{
System.out.println("Event date " + mm + "/" + dd + "/2014");
}
// Overloaded method display the month and day and year
public static void displayDate(int mm, int dd, int yy)
{
System.out.println("Event date " + mm + "/" + dd + "/" + yy);
}
}
C:UsersChristopherDocumentsNetBeansProjectsJRVampedsrcCarInsurancePolicy.java
/*
Open a new file in your text editor, and start the CarInsurancePolicy class as follows.
The class contains three fields that hold a policy number, the number of payments the
policyholder will make annually, and the policyholder’s city of residence.
*/
public class CarInsurancePolicy
{
private int policyNumber;
private int numPayments;
private String residentCity;
// Create a constructor that requires parameters for all three data fields
public CarInsurancePolicy(int num, int payments, String city)
{
policyNumber = num;
numPayments = payments;
residentCity = city;
}
/*
Suppose the agency that sells car insurance policies is in the city of Mayfield.
Create a two-parameter constructor that requires only a policy number and the
number of payments. This constructor assigns Mayfield to residentCity.
*/
public CarInsurancePolicy(int num, int payments)
{
policyNumber = num;
numPayments = payments;
residentCity = "Port Harcourt";
}
/*
Add a third constructor that requires only a policy number parameter. This
constructor uses the default values of two annual payments and Mayfield as the
resident city. (Later in this chapter, you will learn how to eliminate the duplicated
assignments in these constructors.)
*/
public CarInsurancePolicy(int num)
{
policyNumber = num;
numPayments = 2;
residentCity = "Port Harcourt";
}
/*
Add a display() method that outputs all the insurance policy data:
*/
public void display()
{
System.out.println("Policy #" + policyNumber + ". " +
numPayments + " payments annually. Driver resides in " +
residentCity + ".");
}
}
C:UsersChristopherDocumentsNetBeansProjectsJRVampedsrcCreatedPolicies.java
/*
Open a new text file to create a short application that demonstrates the
constructors at work. The application declares three CarInsurancePolicy
objects using a different constructor version each time. Type the following
code:
*/
public class CreatedPolicies
{
public static void main(String[] args)
{
CarInsurancePolicy first = new CarInsurancePolicy(123);
CarInsurancePolicy second = new CarInsurancePolicy(456, 4);
CarInsurancePolicy third = new CarInsurancePolicy
(789, 12, "Port Harcourt");
// Display each object, and add closing curly braces for the method
// and the class:
first.display();
second.display();
third.display();
}
}
Example demonstrating the creation of classes and instantiating objects
from them.
The Employee class below with four data fields and the methods for
getting and setting data into the fields
package MyJavaLab;
public class Employee
{
private int empNum; //These are the data fields for the Employee
Class
private String empLastName;
private String empFirstName;
private double empSalary;
public int getEmpNum() //These are the methods for setting and
retrieving data
{ //from the fields in Employee class
return empNum;
}
public void setEmpNum(int empNo)
{
empNum = empNo;
}
public String getEmpLastName()
{
return empLastName;
}
public void setEmpLastName(String lastName)
{
empLastName = lastName;
}
public String getEmpFirstName()
{
return empFirstName;
}
public void setEmpFirstName(String firstName)
{
empFirstName = firstName;
}
public double getEmpSalary()
{
return empSalary;
}
public void setEmpSalary(double salary)
{
empSalary = salary;
}
}
The class below instantiate objects (md and bdc) of the Employee class
and access the Employee class methods using the identifier, a dot and a
method call (to call the methods in the Employee class).
package MyJavaLab;
public class EmployeesExample
{
public static void main(String[] args)
{
Employee md = new Employee(); //The Employee MD
Employee bdc = new Employee(); //The Employee is BDC
md.setEmpNum(345);
bdc.setEmpNum(456);
md.setEmpLastName("Akinlade");
md.setEmpFirstName("Christopher");
bdc.setEmpLastName("Kolawole");
bdc.setEmpFirstName("Michael");
md.setEmpSalary(56408.55);
System.out.println("The MD's employee # is : " + md.getEmpNum());
System.out.println("The MD's name is " + md.getEmpLastName() + " " +
md.getEmpFirstName());
System.out.println("And his starting salary is $" + md.getEmpSalary());
System.out.println("");
System.out.println("The BDC's employee # is : " + bdc.getEmpNum());
System.out.println("The BDC's name is " + bdc.getEmpLastName() + " "
+ bdc.getEmpFirstName());
System.out.println("And his starting salary is $" + bdc.getEmpSalary());
}
}
CREATING CLASSES, DECLARING & USING OBJECTS
SECTION1:
Creating a Class That Contains Instance Fields and Methods
In this section, you create a class to store information about event services
offered at
Paradise Day Spa.
1. Open a new document in your text editor, and type the following class
header and the curly braces to surround the class body:
public class SpaServices
{
}
2. Between the curly braces for the class, insert two private data fields that will
hold data about a spa service:
private String serviceDescription;
private double price;
3. Within the class’s curly braces and after the field declarations, enter the
following two methods that set the field values. The setServiceDescription()
method accepts a String parameter and assigns it to the serviceDescription
field for each object that eventually will be instantiated. Similarly, the setPrice()
method accepts a double parameter and assigns it to the price field. Note that
neither of these methods is static.
public void setServiceDescription(String service)
{
serviceDescription = service;
}
public void setPrice(double pr)
{
price = pr;
}
4. Next, add two methods that retrieve the field values as follows:
public String getServiceDescription()
{
return serviceDescription;
}
public double getPrice()
{
return price;
}
5. Save the file as SpaServices.java, compile it, and then correct any syntax
errors. Remember, you cannot run this file as a program because it does not
contain a public static main() method. In the next section, this class is used to
create objects.
SECTION 2
Declaring and Using Objects
In section 1, you created a class named SpaServices. Now you create an
application that instantiates and uses SpaServices objects.
1. Open a new file in your text editor, and type the import statement needed
for an interactive program that accepts user keyboard input:
import java.util.Scanner;
2. Create the shell for a class named CreateSpaServices:
public class CreateSpaServices
{
}
3. Between the curly braces of the CreateSpaServices class, create the shell
for a main() method for the application:
public static void main(String[] args)
{
}
4. Within the main() method, declare variables to hold a service description
and price that a user can enter from the keyboard:
String service;
double price;
5. Next, declare three objects. Two are SpaService objects that use the class
you created in the prior set of “You Do It” steps. The third object uses the built-
in Java Scanner class. Both classes use the new operator to allocate memory
for their objects, and both call a constructor that has the same name as the
class. The difference is that the Scanner constructor requires an argument
(System.in), but the SpaService class does not.
SpaServices firstService = new SpaService();
SpaServices secondService = new SpaService();
Scanner keyboard = new Scanner(System.in);
6. In the next statements, you prompt the user for a service, accept it from the
keyboard, prompt the user for a price, and accept it from the keyboard.
System.out.print("Enter first service >> ");
service = keyboard.nextLine();
System.out.print("Enter price >> ");
price = keyboard.nextDouble();
7. Recall that the setServiceDescription() method in the SpaService class is
nonstatic, meaning it is used with an object, and that it requires a String
argument. Write the statement that sends the service the user entered to the
setServiceDescription() method for the firstService object:
firstService.setServiceDescription(service);
8. Similarly, send the price the user entered to the setPrice() method for the
firstService object. Recall that this method is nonstatic and requires a double
argument.
firstService.setPrice(price);
9. Make a call to the nextLine() method to remove the Enter key that remains
in the input buffer after the last numeric entry. Then repeat the prompts, and
accept data for the second SpaServices object.
keyboard.nextLine();
System.out.print("Enter second service >> ");
service = keyboard.nextLine();
System.out.print("Enter price >> ");
price = keyboard.nextDouble();
secondService.setServiceDescription(service);
secondService.setPrice(price);
10. Display the details for the firstService object.
System.out.println("First service details:");
System.out.println(firstService.getServiceDescription() +
" $" + firstService.getPrice());
11. Display the details for the secondService object.
System.out.println("Second service details:");
System.out.println(secondService.getServiceDescription() +
" $" + secondService.getPrice());
12. Save the file as CreateSpaServices.java. Compile and execute the
program. The figure below shows a typical execution. Make sure you
understand how the user’s entered values are assigned to and retrieved from
the two SpaService objects.
Q1 – Page 234. Create a class named FormLetterWriter that includes two
overloaded methods named displaySalutation(). The first method takes one String
parameter that represents a customer’s last name, and it displays the salutation “Dear
Mr. or Ms.”followed by the last name. The second method accepts two String
parameters that represent a first and last name, and it displays the greeting “Dear”
followed by the first name, a space, and the last name. After each salutation, display
the rest of a short business letter: “Thank you for your recent order.” Write a main()
method that tests each overloaded method. Save the file as FormLetterWriter.java.
C:UsersChristopherDocumentsNetBeansProjectsJRVampedsrcFormLetterWriter.java
public class FormLetterWriter
{
public static void main(String[] args)
{
// Declair two String variables
String firstName = "Mfon";
String lastName = "Akinlade";
// The first overloaded method call
displaySalutation(lastName);
// The second overloaded method call
displaySalutation(firstName, lastName);
System.out.println("Thanks for your order. ");
}
// First overloaded method
public static void displaySalutation(String firstName)
{
System.out.println("Dear Mr. or Ms. " + firstName);
}
// Second overloaded method
public static void displaySalutation(String firstName, String lastName)
{
System.out.println("Dear " + firstName + " " + lastName);
}
}
Q2 page 235. Create a class named Billing that includes three overloaded
computeBill() methods for a photo book store.
 When computeBill() receives a single parameter, it represents the price of one
photo book ordered. Add 8% tax, and return the total due.
 When computeBill() receives two parameters, they represent the price of a
photo book and the quantity ordered. Multiply the two values, add 8% tax, and
return the total due.
 When computeBill() receives three parameters, they represent the price of a
photo book, the quantity ordered, and a coupon value. Multiply the quantity
and price, reduce the result by the coupon value, and then add 8% tax and
return the total due. Write a main() method that tests all three overloaded
methods. Save the application as Billing.java.
C:UsersChristopherDocumentsNetBeansProjectsJRVampedsrcBilling.java
public class Billing
{
public static void main(String[] args)
{
//Declare three variables
double price;
double couponValue;
int qty;
// the variable values below will be used to test the
// overloaded methods
price = 100.00;
qty = 100;
couponValue = 200;
// The three overloaded methods
totalBill(price);
totalBill(price, qty);
totalBill(price, qty, couponValue);
}
// First Overlaoded method with price as single argument
public static void totalBill(double price)
{
double totalDue;
double taxPaid;
taxPaid = 8 * price / 100;
totalDue = price + taxPaid;
System.out.println("You ordered 1 copy, Cost = $" + totalDue +
" Inclusive Sales Tax: = $" + taxPaid);
}
// Second Overlaoded method with price and quantity as arguments
public static void totalBill(double price, int qty)
{
double percentTax;
double preTaxAmount;
double totalDue;
double taxPaid;
preTaxAmount = price * qty;
taxPaid = 8 * preTaxAmount / 100;
totalDue = preTaxAmount + taxPaid;
System.out.println("You ordered " + qty + " copies at a Total Cost of" +
" $" + totalDue + " Inclusive Sales Tax: = $" + taxPaid);
}
// Third overloaded method with price, quantity and coupon value as
// arguments
public static void totalBill(double price, int qty, double couponValue)
{
double totalDue;
double preCouponAmount;
double preTaxAmount;
double taxPaid;
preCouponAmount = price * qty;
preTaxAmount = preCouponAmount - couponValue;
taxPaid = 8 * preTaxAmount / 100;
totalDue = preTaxAmount + taxPaid;
System.out.println("You ordered " + qty + " copies, at a Total Cost "
+ "of = $" + totalDue + ", inclusive Tax: = $" + taxPaid);
}
}
Page 235 (Java Programming – 7th Ed – By Joyce Farrell
3. a. Create a BirdSighting class for the Birmingham Birdwatcher’s Club that
includes data fields for a bird species sighted, the number seen, and the day
of the year. Forexample, April 1 is the 91st day of the year, assuming it is not a
leap year. The classalso includes methods to get each field. In addition, create
a default constructor that automatically sets the species to “robin” and the
number and day to 1. Save the file as BirdSighting.java. Create an
application named TestBirdSighting that demonstrates that each method
works correctly. Save the file as TestBirdSighting.java.
b. Create an additional overloaded constructor for the BirdSighting class you
created in Exercise 3a. This constructor receives parameters for each of the
data fields and assigns them appropriately. Add any needed statements to the
TestBirdSighting application to ensure that the overloaded constructor works
correctly, save it, and then test it.
c. Create a class with the same functionality as the BirdSighting class, but
create the default constructor to call the three-parameter constructor. Save the
class as BirdSighting2.java. Create an application to test the new version of
the class and name it TestBirdSighting2.java.
//Below is the BirdSighting.java class
C:UsersChristopherDocumentsNetBeansProjectsJRVampedsrcBirdSighting.jaa
public class BirdSighting
{
// Declare the private data fields
private String species;
private int numBirdsSeen;
private int dayOfYear;
// The default constructor
public BirdSighting()
{
species = "robin";
numBirdsSeen = 1;
dayOfYear = 1;
}
// Constructor and methods that receive values
public BirdSighting(String specs, int birdsCount, int day)
{
species = specs;
numBirdsSeen = birdsCount;
dayOfYear = day;
}
// Get methods
public String getSpecies()
{
return species;
}
public int getNumBirdsSeen()
{
return numBirdsSeen;
}
public int getDayOfYear()
{
return dayOfYear;
}
// Set methods
public void setSpecies(String specs)
{
species = specs;
}
public void setNumBirdsSeen(int numOfBirds)
{
numBirdsSeen = numOfBirds;
}
public void setDayOfYear(int day)
{
dayOfYear = day;
}
}
//The TestBirdSighting.java main class that uses the code in the previous
section
C:UsersChristopherDocumentsNetBeansProjectsJRVampedsrcTestBirdSighting.java
import java.util.Scanner;
public class TestBirdSighting
{
public static void main(String[] args)
{
// Create default BirdSighting object
BirdSighting defaultSight = new BirdSighting();
String species = defaultSight.getSpecies();
int numOfBirdsSeen = defaultSight.getNumBirdsSeen();
int dayOfYear = defaultSight.getDayOfYear();
System.out.println("nDEFAULT Bird Sightings with parameters" +
" in BirdSighting.java class");
System.out.println(numOfBirdsSeen + " birds of the " + species +
" species were seen on the " + dayOfYear + " of the year n");
System.out.println("DETAILS FOR FIRST BIRD SIGHTING");
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter the bird species name:>> ");
species = keyboard.next();
System.out.print("How many of the species did you see? >> ");
numOfBirdsSeen = keyboard.nextInt();
System.out.print("Enter the day of the year:>> ");
dayOfYear = keyboard.nextInt();
// Create the first BirdSighting object, firsSight
BirdSighting firstSight = new BirdSighting(species, numOfBirdsSeen,
dayOfYear);
System.out.println("nOn the First Sighting ");
System.out.println(numOfBirdsSeen + " birds of the " + species +
" species were seen on the " + dayOfYear + " day of the year");
System.out.println(" ~~~~~~~~~~~~~~~~~~~~~~~~~~");
System.out.println("DETAILS FOR SECOND BIRD SIGHTING");
//Scanner keyboard = new Scanner(System.in);
System.out.print("Enter the bird species name:>> ");
species = keyboard.next();
System.out.print("How many of the species did you see? >> ");
numOfBirdsSeen = keyboard.nextInt();
System.out.print("Enter the day of the year:>> ");
dayOfYear = keyboard.nextInt();
// Create the first BirdSighting object, firsSight
BirdSighting secondSight = new BirdSighting(species, numOfBirdsSeen,
dayOfYear);
System.out.println("nOn the Second Sighting ");
System.out.println(numOfBirdsSeen + " birds of the " + species +
" species were seen on the " + dayOfYear + " day of the year");
System.out.println(" ~~~~~~~~~~~~~~~~~~~~~~~~~~");
}
}
3c
C:UsersChristopherDocumentsNetBeansProjectsJRVampedsrcBirdSighting2.java
public class BirdSighting2
{
private String species;
private int numberSeen;
private int dayOfYear;
//Method with constructors that take parameters when objects are created
public BirdSighting2(String specs, int numSeen, int day)
{
species = specs;
numberSeen = numSeen;
dayOfYear = day;
}
// Get methods
public String getSpecies()
{
return species;
}
public int getNumberSeen()
{
return numberSeen;
}
public int getDayOfYear()
{
return dayOfYear;
}
//Set methods
public void setSpecies(String specs)
{
species = specs;
}
public void setNumberSeen(int numSeen)
{
numberSeen = numSeen;
}
public void setDayOfYear(int day)
{
dayOfYear = day;
}
}
C:UsersChristopherDocumentsNetBeansProjectsJRVampedsrcTestBirdSighting2.java
import java.util.Scanner;
public class TestBirdSighting2
{
public static void main(String[] args)
{
System.out.println("DETAILS FOR FIRST BIRDS SIGHTING");
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter the bird species name;>> ");
String species = keyboard.next();
System.out.print("How many of the species did you see?>> ");
int numberSeen = keyboard.nextInt();
System.out.print("Enter the day of the year;>> ");
int dayOfYear = keyboard.nextInt();
BirdSighting2 firstSight = new BirdSighting2(species, numberSeen, dayOfYear);
System.out.println("");
System.out.println("On the First Sighting: ");
System.out.println(numberSeen + " birds of the " + species +
" species were seen on day " + dayOfYear + " of the year");
System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
System.out.println("DETAILS FOR SECOND BIRDS SIGHTING");
Scanner keyEntry = new Scanner(System.in);
System.out.print("Enter the bird species name;>> ");
species = keyEntry.next();
System.out.print("How many of the species did you see?>> ");
numberSeen = keyEntry.nextInt();
System.out.print("Enter the day of the year;>> ");
dayOfYear = keyEntry.nextInt();
BirdSighting2 secondSight = new BirdSighting2(species, numberSeen,
dayOfYear);
System.out.println("");
System.out.println("On the Second Sighting: ");
System.out.println(numberSeen + " birds of the " + species +
" species were seen on day " + dayOfYear + " of the year");
System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
System.out.println("DETAILS FOR THIRD BIRDS SIGHTING");
Scanner input = new Scanner(System.in);
System.out.print("Enter the bird species name;>> ");
species = input.next();
System.out.print("How many of the species did you see?>> ");
numberSeen = input.nextInt();
System.out.print("Enter the day of the year;>> ");
dayOfYear = input.nextInt();
BirdSighting2 thirdSight = new BirdSighting2(species, numberSeen, dayOfYear);
System.out.println("");
System.out.println("On the Third Sighting: ");
System.out.println(numberSeen + " birds of the " + species +
" species were seen on day " + dayOfYear + " of the year");
System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
System.exit(0);
}
}
4. a. Create a class named BloodData that includes fields that hold a blood type
(the four blood types are O, A, B, and AB) and an Rh factor (the factors are +
and –). Create a default constructor that sets the fields to “O” and “+”, and an
overloaded constructor that requires values for both fields. Include get and set
methods for each field. Save this file as BloodData.java. Create an application
named TestBloodData that demonstrates that each method works correctly.
Save the
application as TestBloodData.java.
b. Create a class named Patient that includes an ID number, age, and
BloodData. Provide a default constructor that sets the ID number to “0”, the age
to 0, and the BloodData to “O” and “+”. Create an overloaded constructor that
provides values for each field. Also provide get methods for each field. Save
the file as Patient.java. Create an application named TestPatient that
demonstrates that each method works correctly, and save it as
TestPatient.java.
//BloodData class
C:UsersChristopherDocumentsNetBeansProjectsJRVampedsrcBloodData.java
public class BloodData
{
// Create two private data fields
private String bloodType;
private String rhesusFactor;
// Constructor with default values
public BloodData()
{
bloodType = "O";
rhesusFactor = "+";
}
// Constructor that receive values
public BloodData(String type, String factor)
{
bloodType = type;
rhesusFactor = factor;
}
// Get methods
public String getBloodType()
{
return bloodType;
}
public String getRhesusFactor()
{
return rhesusFactor;
}
// Set methods
public void setBloodType(String type)
{
bloodType = type;
}
public void setRhesusFactor(String factor)
{
rhesusFactor = factor;
}
}
//TestBloodData main class
C:UsersChristopherDocumentsNetBeansProjectsJRVampedsrcTestBloodData.java
import java.util.Scanner;
public class TestBloodData
{
public static void main(String[] args)
{
// Create default BloodData object that doesn't take parameters
BloodData defaultType = new BloodData();
String bloodType = defaultType.getBloodType();
String rhesusFactor = defaultType.getRhesusFactor();
// Default Blood Data Details
System.out.println("BloodGroup is:>> " + bloodType + " ; Rhesus factor is:>> " +
rhesusFactor + "n");
// Input data for the first BloodData object
Scanner input = new Scanner(System.in);
System.out.print("Enter first patient's Blood Group:>> ");
bloodType = input.next();
System.out.print("Enter first patient's Rhesus Factor:>> ");
rhesusFactor = input.next();
// Create the first BloodData object
BloodData firstBloodData = new BloodData(bloodType, rhesusFactor);
bloodType = firstBloodData.getBloodType();
rhesusFactor = firstBloodData.getRhesusFactor();
//Output of first patient's Blood Data
System.out.println("");
System.out.println("Below is the first patient's blood data");
System.out.println("BloodGroup is:>> " + bloodType + " ; RhesusFactor is:>> " +
rhesusFactor);
System.out.println("~~~~~~~~~~~~~~~~~~~~ ");
// Input data for the second BloodData object
System.out.print("Enter second patient's Blood Group:>> ");
bloodType = input.next();
System.out.print("Enter second patient's Rhesus Factor:>> ");
rhesusFactor = input.next();
// Create the second BloodData object
BloodData secondBloodData = new BloodData(bloodType, rhesusFactor);
bloodType = secondBloodData.getBloodType();
rhesusFactor = secondBloodData.getRhesusFactor();
//Output of second patient's Blood Data
System.out.println("");
System.out.println("Below is the second patient's blood data");
System.out.println("BloodGroup is:>> " + bloodType + " ; RhesusFactor is:>> " +
rhesusFactor);
System.out.println("~~~~~~~~~~~~~~~~~~~~ ");
}
}
Part B
C:UsersChristopherDocumentsNetBeansProjectsJRVampedsrcPatient.java
public class Patient
{
// Create three private data fields, the third f
// ield is an object of the BloodData class
private int idNum;
private int age;
private BloodData bldData;
// Constructor that returns default values
public Patient()
{
bldData = new BloodData("O", "+");
idNum = 0;
age = 0;
}
// Constructor that return user entered values
public Patient(int idNo, int yAge, String bloodType, String rhesusFactor)
{
bldData = new BloodData(bloodType, rhesusFactor);
age = yAge;
idNum = idNo;
}
// get methods
public String getBldGroup()
{
return bldData.getBloodType();
}
public String getRhesusFactor()
{
return bldData.getRhesusFactor();
}
public int getAge()
{
return age;
}
public int getIdNum()
{
return idNum;
}
// set methods
public void setIdNum(int idNo)
{
idNum = idNo;
}
public void setAge(int yAge)
{
age = yAge;
}
}
PARTB
C:UsersChristopherDocumentsNetBeansProjectsJRVampedsrcTestPatient.java
public class TestPatient
{
public static void main(String[] args)
{
Patient firstPatient = new Patient();
int idNum = firstPatient.getIdNum();
int age = firstPatient.getAge();
System.out.println("DEFAULT PATIENT BLOOD TYPE DETAILS");
System.out.println("Age:>>" + age );
System.out.println("ID#:>> " + idNum);
System.out.println("Blood Group:>> " + firstPatient.getBldGroup());
System.out.println("Rhesus Factor:>> " + firstPatient.getRhesusFactor());
Patient secondPatient = new Patient(220909, 39, "O", "+");
System.out.println("");
System.out.println("FIRST PATIENT BLOOD TYPE DETAILS");
System.out.println("Age:>> " + secondPatient.getAge());
System.out.println("ID#:>> " + secondPatient.getIdNum());
System.out.println("Blood Group:>> " + secondPatient.getBldGroup());
System.out.println("Rhesus Factor:>> " + secondPatient.getRhesusFactor());
}
}
Java   small steps - 2019
Page 236
6. a. Create a class named Circle with fields named radius, diameter, and
area. Include a constructor that sets the radius to 1 and calculates the other
two values. Also include methods named setRadius()and getRadius(). The
setRadius() method not only sets the radius but also calculates the other two
values. (The diameter of a circle is twice the radius, and the area of a circle is
pi multiplied by the square of the radius. Use the Math class PI constant for
this calculation.) Save the class as Circle.java.
b. Create a class named TestCircle whose main() method declares several
Circle objects. Using the setRadius() method, assign one Circle a small radius
value, and assign another a larger radius value. Do not assign a value to the
radius of the third circle; instead, retain the value assigned at construction.
Display all the values for all the Circle objects. Save the application as
TestCircle.java.
Circle.java class
C:UsersChristopherDocumentsNetBeansProjectsJRVampedsrcCircle.java
public class Circle
{
// Declare data field variables associated with a circle
private double radius;
private double diameter;
private double area;
// Create a default constructor
public Circle()
{
radius = 1.0;
diameter = 2 * radius;
area = Math.PI * radius * radius;
}
// Constructor that receive radius as a parameter
public Circle(double rad)
{
radius = rad;
diameter = 2 * rad;
area = Math.PI * rad * rad;
}
//get methods
public double getDiameter(double diam)
{
return diameter = 2 * radius;
}
public double getArea(double area)
{
return area = Math.PI * radius * radius;
}
public double getRadius()
{
return radius;
}
// Set method for setting radius of circle
public void setRadius(double rad)
{
radius = rad;
}
}
TestCircle.java class
C:UsersChristopherDocumentsNetBeansProjectsJRVampedsrcTestCircle.java
import java.util.Scanner;
public class TestCircle
{
public static void main(String[] args)
{
// Creat a Scanner object for user input
Scanner input = new Scanner(System.in);
System.out.print("Enter the radius of the FIRST cicle:>> ");
double radius = input.nextDouble();
// Instantiate first circle object
Circle firstCircle = new Circle(radius);
radius = firstCircle.getRadius();
double diameter = firstCircle.getDiameter(radius);
double area = firstCircle.getArea(radius);
System.out.println("Radius of firstCircle is:>> " + radius + " cm");
System.out.println("Diameter of firstCircle is:>> " + diameter + " cm");
System.out.println("Area of firstCircle is:>> " + area + " cm.sq");
System.out.println(" ");
System.out.print("Enter the radius of the SECOND circle:>> ");
double radius2 = input.nextDouble();
// instantiate second circle
Circle secondCircle = new Circle(radius2);
double diameter2 = secondCircle.getDiameter(radius2);
double area2 = secondCircle.getArea(radius2);
System.out.println("Radius of secondCircle is:>> " + radius2 + " cm");
System.out.println("Diameter of secondCircle is:>> " + diameter2 + " cm");
System.out.println("Area of firstCircle is:>> " + area2 + " cm.sq");
System.out.println(" ");
Circle defaultCircle = new Circle();
// NOTE: THe radius and the diameter of the default circle are
// those provided by the default constructor in Circle.java class
// Users don't have to input values for these parameters
double radiusD = defaultCircle.getRadius();
double diameterD = defaultCircle.getDiameter(radius);
double areaD = defaultCircle.getArea(radius);
System.out.println("DEFAULT VALUES ARE AUTO GENERATED");
System.out.println("AS PAR CONSTRUCTOR IN THE Circle.java class ");
System.out.println( "Radius of defaultCircle is: = " + radiusD + " cm");
System.out.println( "Diameter of defaultCircle is: = " + diameterD + " cm");
System.out.println( "AREA of DEFAULT circle is: = " + areaD + " cm.sq");
System.out.println( " ");
}
}
5. a. Create a class for the Tip Top Bakery named Bread with data fields for bread
type (such as “rye”) and calories per slice. Include a constructor that takes
parameters for each field, and include get methods that return the values of the fields.
Also include a public final static String named MOTTO and initialize it to The staff of
life. Write an application named TestBread to instantiate three Bread objects with
different values, and then display all the data, including the motto, for each object.
Save both the Bread.java and TestBread.java files.
//Bread class
C:UsersChristopherDocumentsNetBeansProjectsJRVampedsrcBread.java
public class Bread
{
//Two private data fields and one public data fields declared
private String breadType;
private int calories;
public static final String MOTTO = "The staff of life.";
//Constructor for Bread type
public Bread(String type, int calori)
{
breadType = type;
calories = calori;
}
// get methods
public String getBreadType()
{
return breadType;
}
public int getCalories()
{
return calories;
}
// set methods
public void setBreadType(String type)
{
breadType = type;
}
public void setCalories(int calori)
{
calories = calori;
}
}
TestBread class
C:UsersChristopherDocumentsNetBeansProjectsJRVampedsrcTestBread.java
import java.util.Scanner;
public class TestBread
{
public static void main(String[] args)
{
// Create a Scanner object for user inputs;
Scanner input = new Scanner(System.in);
// Enter the first bread type
System.out.print("Enter the first bread type:>> ");
String breadType = input.nextLine();
// Enter the number of calories for this bread type
System.out.print("Enter first bread calories:>> ");
int calories = input.nextInt();
System.out.println(" ");
// Create a new Bread object
Bread wBread;
wBread = new Bread(breadType, calories);
breadType = wBread.getBreadType();
calories = wBread.getCalories();
System.out.println(breadType + " bread has " + calories +
" calories per loaf ");
System.out.println(Bread.MOTTO);
System.out.println(" ~~~~~~~~~ ");
input.nextLine(); // to consume the line left from above
// Enter the second bread type
System.out.print("Enter the second bread type:>> ");
String breadType2 = input.nextLine();
// Enter the number of calories for this bread type
System.out.print("Enter second bread calories:>> ");
int calories2 = input.nextInt();
System.out.println(" ");
// Create a new Bread object
Bread cBread;
cBread = new Bread(breadType2, calories2);
breadType2 = cBread.getBreadType();
calories2 = cBread.getCalories();
System.out.println(breadType2 + " bread has " + calories2 +
" calories per loaf ");
System.out.println(Bread.MOTTO);
System.out.println(" ~~~~~~~~~ ");
input.nextLine(); // to consume the line left from above
// Enter the third bread type
System.out.print("Enter the third bread type:>> ");
String breadType3 = input.nextLine();
// Enter the number of calories for this bread type
System.out.print("Enter third bread caloies:>> ");
int calories3 = input.nextInt();
System.out.println(" ");
// Create a new Bread object
Bread oatBread;
oatBread = new Bread(breadType3, calories3);
breadType3 = oatBread.getBreadType();
calories3 = oatBread.getCalories();
System.out.println(breadType3 + " bread has " + calories3 +
" calories per loaf ");
System.out.println(Bread.MOTTO);
System.out.println(" ~~~~~~~~~ ");
}
}
5 b. Create a class named SandwichFilling. Include a field for the filling type
(such as “egg salad”) and another for the calories in a serving. Include a
constructor that takes parameters for each field, and include get methods that
return the values of the fields. Write an application named TestSandwichFilling
to instantiate three SandwichFilling objects with different values, and then
display all the data for each object. Save both the SandwichFilling.java and
TestSandwichFilling.java files.
//SandwichFilling class
C:UsersChristopherDocumentsNetBeansProjectsJRVampedsrcSandwichFilling.java
public class SandwichFilling
{
private String fillType;
private int calories;
// Constructor take values from parameters
public SandwichFilling (String fill, int calori)
{
fillType = fill;
calories = calori;
}
// get methods
public String getFillType()
{
return fillType;
}
public int getCalories()
{
return calories;
}
public void setFillType(String fill)
{
fillType = fill;
}
public void setCalories(int calori)
{
calories = calori;
}
}
//TestSandwichFilling.java
C:UsersChristopherDocumentsNetBeansProjectsJRVampedsrcTestSandwichFilling.java
import java.util.Scanner; // For user data input
public class TestSandwichFilling
{
public static void main(String[] args)
{
// Create Scanner object for user inputs
Scanner input = new Scanner(System.in);
System.out.print("Enter First Sandwich filling:>> ");
String fillType = input.nextLine();
System.out.print("Enter the calories per serving:>> ");
int calories = input.nextInt();
System.out.println(" ");
SandwichFilling firstFill = new SandwichFilling(fillType, calories);
fillType = firstFill.getFillType();
calories = firstFill.getCalories();
System.out.println(fillType + " Sandwhich filling has " + calories +
" calories per serving. ");
System.out.print(" ");
System.out.println("~~~~~~~~~~~");
System.out.print("Enter Second Sandwich filling:>> ");
String fillType2 = input.next();
System.out.print("Enter the calories per serving:>> ");
int calories2 = input.nextInt();
System.out.println(" ");
SandwichFilling secondFill = new SandwichFilling(fillType2, calories2);
fillType2 = secondFill.getFillType();
calories2 = secondFill.getCalories();
System.out.println(fillType2 + " Sandwhich filling has " + calories2 +
" calories per serving. ");
System.out.println("~~~~~~~~~~~");
System.out.print("Enter Third Sandwich filling:>> ");
String fillType3 = input.next();
System.out.print("Enter the calories per serving:>> ");
int calories3 = input.nextInt();
System.out.println(" ");
SandwichFilling thirdFill = new SandwichFilling(fillType3, calories3);
fillType3 = thirdFill.getFillType();
calories3 = thirdFill.getCalories();
System.out.println(fillType3 + " Sandwhich filling has " + calories3 +
" calories per serving. ");
System.out.println("~~~~~~~~~~~");
}
}
5c. Create a class named Sandwich. Include a Bread field and a SandwichFilling
field. Include a constructor that takes parameters for each field needed in the two
objects and assigns them to each object’s constructor. Write an application named
TestSandwich to instantiate three Sandwich objects with different values, and then
display all the data for each object, including the total calories in a Sandwich,
assuming that each Sandwich is made using two slices of Bread. Save both the
Sandwich.java and TestSandwich.java files.
//Sandwich.java
C:UsersChristopherDocumentsNetBeansProjectsJRVampedsrcSandywich.java
public class Sandywich
{
private Bread bread;
private SandwichFilling fill;
/**
* The Sandywich class has four data fields, two from the Bread
* class and two from the SandwichFilling class that were created
* and used in previous questions
*/
public Sandywich(String breadType, int caloriesB, String fillType, int caloriesF)
{
// Create a new Bread object from the Bread class and a
// new SandwichFilling object from SandwichFilling
bread = new Bread(breadType, caloriesB);
fill = new SandwichFilling(fillType, caloriesF);
}
/** It is not necessary to get methods for the individual data field separately
* Instead, use is made of the get methods for the Bread and SandwichFilling
* classes. Also, individual set methods are no longer needed because the public
* methods in the Bread and SandwichFilling classes will be used to access their
* respective private fields.
*/
// get methods
public String getBreadType()
{
return bread.getBreadType();
}
public int getCaloriesB()
{
return bread.getCalories();
}
public String getFillType()
{
return fill.getFillType();
}
public int getCaloriesF()
{
return fill.getCalories();
}
}
//TestSandywich.java class
C:UsersChristopherDocumentsNetBeansProjectsJRVampedsrcTestSandywich.java
import java.util.Scanner;
public class TestSandywich
{
public static void main(String[] args)
{
// Input the bread type and the calories per serving fo bread
Scanner input = new Scanner(System.in);
System.out.print("Enter the breadType:>> ");
String breadType = input.next();
System.out.print("Enter the calories per bread serving:>> ");
int caloriesB = input.nextInt();
System.out.print("Enter the sandwich filling:>> ");
String fillType = input.next();
System.out.print("Enter the calories per sandwich serving:>> ");
int caloriesF = input.nextInt();
// Create a new Sandywich object
Sandywich tasteOne = new Sandywich(breadType, caloriesB, fillType, caloriesF);
//Total calories per sandwichOne is calculated below
int totalCalories = 2 * caloriesB + caloriesF;
System.out.println("");
System.out.println("Bread type is: "+ tasteOne.getBreadType());
System.out.println("Calories per bread slice: " + tasteOne.getCaloriesB());
System.out.println("Sandwich filling type: " + tasteOne.getFillType());
System.out.println("Calories per sandwich filling: " + tasteOne.getCaloriesF());
System.out.println("Calories per sandwichOne: = " + totalCalories);
System.out.println(" ~~~~~~~~~~");
System.out.print("Enter the breadType:>> ");
String breadType2 = input.next();
System.out.print("Enter the calories per bread slice:>> ");
int caloriesB2 = input.nextInt();
System.out.print("Enter the sandwich filling:>> ");
String fillType2 = input.next();
System.out.print("Enter the calories per sandwich filling;>> ");
int caloriesF2 = input.nextInt();
Sandywich tasteTwo = new Sandywich(breadType2, caloriesB2, fillType2,
caloriesF2);
//Total calories per sandwichTwo is calculated below
int totalCalories2 = 2 * caloriesB2 + caloriesF2;
System.out.println(" ");
System.out.println("Bread type is: "+ tasteTwo.getBreadType());
System.out.println("Calories per bread slice: " + tasteTwo.getCaloriesB());
System.out.println("Sandwich filling type: " + tasteTwo.getFillType());
System.out.println("Calories per sandwich filling: " + tasteTwo.getCaloriesF());
System.out.println("Calories per sandwichTwo: = " + totalCalories2);
System.out.println(" ~~~~~~~~~~");
System.out.print("Enter the breadType:>> ");
String breadType3 = input.next();
System.out.print("Enter the calories per bread serving:>> ");
int caloriesB3 = input.nextInt();
System.out.print("Enter the sandwich filling:>> ");
String fillType3 = input.next();
System.out.print("Enter the calories per sandwich filling;>> ");
int caloriesF3= input.nextInt();
Sandywich tasteThree = new Sandywich(breadType3, caloriesB3, fillType3,
caloriesF3);
//Total calories per sandwichThree is calculated below
int totalCalories3 = 2 * caloriesB3 + caloriesF3;
System.out.println("");
System.out.println("Bread type is: "+ tasteThree.getBreadType());
System.out.println("Calories per bread slice: " + tasteThree.getCaloriesB());
System.out.println("Sandwich filling type: " + tasteThree.getFillType());
System.out.println("Calories per sandwich filling: " + tasteThree.getCaloriesF());
System.out.println("Calories per sandwichThree: = " + totalCalories3);
System.out.println(" ~~~~~~~~~~");
}
}
7. Write a Java application that uses the Math class to determine the answers for
each of
the following:
a. The square root of 37
b. The sine and cosine of 300
c. The value of the floor, ceiling, and round of 22.8
d. The larger and the smaller of the character “D” and the integer 71
e. A random number between 0 and 20 (Hint: The random() method returns a value
between 0 and 1; you want a number that is 20 times larger.) Save the application as
MathTest.java.
package MyJavaLab;
public class TestMath
{
public static void main(String[] args)
{
double x = 37;
double y = 300;
double z = 22.8;
int number = (int)(20 * Math.random());
System.out.println("Square root of 37 is: " + Math.sqrt (x));
System.out.println("");
System.out.println("Sine of 300 is: " + Math.sin(y));
System.out.println("");
System.out.println("Cosine of 300 is: " + Math.cos(y));
System.out.println("");
System.out.println("floor(22.8) is the largest integral value not greater than 22.8:
" + Math.floor(z));
System.out.println("");
System.out.println("ceil(22.8) is the smallest integral value not less than 22.8: " +
Math.floor(z));
System.out.println("");
System.out.println("round(22.8) is the closest integer value to 22.8: " +
Math.floor(z));
System.out.println("");
System.out.println("Random number is: " + number);
}
}
Worked Example page 200
Creating Overloaded Constructors
In this section, you create a class with overloaded constructors and
demonstrate how
they work.
1. Open a new file in your text editor, and start the CarInsurancePolicy class
as follows. The class contains three fields that hold a policy number, the
number of payments the policy holder will make annually, and the policy
holder’s city of residence.
public class CarInsurancePolicy
{
private int policyNumber;
private int numPayments;
private String residentCity;
2. Create a constructor that requires parameters for all three data fields.
public CarInsurancePolicy(int num, int payments, String city)
{
policyNumber = num;
numPayments = payments;
residentCity = city;
}
3. Suppose the agency that sells car insurance policies is in the city of
Mayfield.
Create a two-parameter constructor that requires only a policy number and
number of payments. This constructor assigns Mayfield to residentCity.
public CarInsurancePolicy(int num, int payments)
{
policyNumber = num;
numPayments = payments;
residentCity = "Mayfield";
}
4. Add a third constructor that requires only a policy number parameter.
This constructor uses the default values of two annual payments and Mayfield
as the resident city. (Later in this chapter, you will learn how to eliminate the
duplicated assignments in these constructors.)
public CarInsurancePolicy(int num)
{
policyNumber = num;
numPayments = 2;
residentCity = "Mayfield";
5. Add a display() method that outputs all the insurance policy data:
public void display()
{
System.out.println("Policy #" + policyNumber + ". " +
numPayments + " payments annually. Driver resides in " +
residentCity + ".");
}
6. Add a closing curly brace for the class. Save the file as
CarInsurancePolicy.java.
7. Open a new text file to create a short application that demonstrates the
constructors at work. The application declares three CarInsurancePolicy
objects using a different constructor version each time. Type the following
code:
public class CreatePolicies
{
public static void main(String[] args)
{
CarInsurancePolicy first = new CarInsurancePolicy(123);
CarInsurancePolicy second = new CarInsurancePolicy(456, 4);
CarInsurancePolicy third = new CarInsurancePolicy
(789, 12, "Newcastle");
8. Display each object, and add closing curly braces for the method and the
class:
first.display();
second.display();
third.display();
}
}
9. Save the file as CreatePolicies.java, and then compile and test the program.
The output appears in Figure 4-23.
}
10. Add a fourth declaration to the CreatePolicies class that attempts to create
a CarInsurancePolicy object using a default constructor:
CarInsurancePolicy fourth = new CarInsurancePolicy();
11. Save and compile the revised CreatePolicies program. The class does not
compile because the CarInsurancePolicy class does not contain a default
constructor. Change the newly added declaration to a comment, compile the
class again, and observe that the class now compiles correctly.
Using the this Reference to Make Constructors More Efficient
In this section, you modify the CarInsurancePolicy class so that its
constructors are more efficient.
1. Open the CarInsurancePolicy.java file. Change the class name to
CarInsurancePolicy2, and immediately save the file as
CarInsurancePolicy2.java.
2. Change the name of the three-parameter constructor from
CarInsurancePolicy() to CarInsurancePolicy2().
3. Replace the constructor that accepts a single parameter for the policy
number with the following constructor. The name of the constructor is changed
from the earlier version, and this one passes the policy number and two
constant values to the three-parameter constructor:
public CarInsurancePolicy2(int num)
{
this(num, 2, "Mayfield");
}
4. Replace the constructor that accepts two parameters (for the policy number
and number of payments) with the following constructor. This constructor has
a new name and passes the two parameters and one constant value to the
three-parameter constructor:
public CarInsurancePolicy2(int num, int payments)
{
this(num, payments, "Mayfield");
}
5. Save the file, and compile it.
6. Open the CreatePolicies.java file that demonstrates the use of the different
constructor versions. Change the class name to CreatePolicies2, and save the
file as CreatePolicies2.java.
7. Add the digit 2 in six places—three times to change the class name
CarInsurancePolicy to CarInsurancePolicy2 when the name is used as a data
type, and in the three constructor calls.
8. Save the file, and then compile and execute it. The output is identical to that
shown in Figure 4-23 in the previous “You Do It” section, but the repetitious
constructor code has been eliminated.
9. You can further reduce the code in the CarInsurancePolicy class by
changing the single-parameter constructor to the following, which removes the
constant "Mayfield" from the constructor call:
public CarInsurancePolicy2(int num)
{
this(num, 2);
}
Now, the single-parameter version calls the two-parameter version and passes
the policy number and the constant 2. In turn, the two-parameter version calls
the three-parameter version, adding "Mayfield" as the city.
10. Save this version of the CarInsurancePolicy2 class, and compile it. Then
recompile the CreatePolicies2.java file, and execute it. The output remains the
same.
Using Static and Nonstatic final Fields (Worked Example on page 213)
In this section, you create a class for the Riverdale Kennel Club to
demonstrate the use
of static and nonstatic final fields. The club enters its dogs in an annual
triathlon event
in which each dog receives three scores in agility, conformation, and
obedience.
1. Open a new file in your text editor, and enter the first few lines for a
DogTriathlonParticipant class. The class contains a final field that holds
the number of events in which the dog participated. Once a final field is set,
it never should change. The field is not static because it is different for each
dog. The class also contains a static field that holds the total cumulative
score for all the participating dogs. The field is not final because its value
increases as each dog participates in the triathlon, but it is static because at
any moment in time, it is the same for all participants.
public class DogTriathlonParticipant
{
private final int NUM_EVENTS;
private static int totalCumulativeScore = 0;
2. Add six private fields that hold the participating dog’s name, the dog’s score
in
three events, the total score, and the average score:
private String name;
private int obedienceScore;
private int conformationScore;
private int agilityScore;
private int total;
private double avg;
3. The constructor for the class requires five parameters—the dog’s name, the
number of events in which the dog participated, and the dog’s scores in the
three events. (After you read the chapter on decision making, you will be able
to ensure that the number of nonzero scores entered matches the number of
events, but for now no such checks will be made.) The constructor assigns
each value to the appropriate field.
public DogTriathlonParticipant(String name,
int numEvents, int score1, int score2, int score3)
{
this.name = name;
NUM_EVENTS = numEvents;
obedienceScore = score1;
conformationScore = score2;
agilityScore = score3;
4. After the assignments, the constructor calculates the total score for the
participant and the participant’s average score. Notice the result of the division
is cast to a double so that any fractional part of the calculated average is not
lost. Also, add the participant’s total score to the cumulative score for all
participants. Recall that this field is static because it should be the same for all
participants at any point in time. After these statements, add a closing curly
brace for the constructor.
total = obedienceScore +
conformationScore + agilityScore;
avg = (double) total / NUM_EVENTS;
totalCumulativeScore = totalCumulativeScore +
total;
}
5. Start a method that displays the data for each triathlon participant.
public void display()
{
System.out.println(name + " participated in " +
NUM_EVENTS +
" events and has an average score of " + avg);
System.out.println(" " + name +
" has a total score of " + total +
" bringing the total cumulative score to " +
totalCumulativeScore);
}
6. Add a closing curly brace for the class. Then, save the file as
DogTriathlonParticipant.java. Compile the class, and correct any errors.
7. Open a new file in your text editor, and then enter the header and opening
and closing curly braces for a class you can use to test the
DogTriathlonParticipant class. Also include a main() method header and
its opening and closing braces.
public class TestDogs
{
public static void main(String[] args)
{
}
}
8. Between the braces of the main() method, declare a
DogTriathlonParticipant object. Provide values for the participant’s name,
number of events, and three scores, and then display the object.
DogTriathlonParticipant dog1 =
new DogTriathlonParticipant("Bowser", 2, 85, 89, 0);
dog1.display();
9. Create and display two more objects within the main() method.
DogTriathlonParticipant dog2 =
new DogTriathlonParticipant("Rush", 3, 78, 72, 80);
dog2.display();
DogTriathlonParticipant dog3 =
new DogTriathlonParticipant("Ginger", 3, 90, 86, 72);
dog3.display();
10. Save the file as TestDogs.java. Compile and execute the program. The
output
looks like Figure 4-36. Visually confirm that each total, average, and
cumulative
total is correct.
11. Experiment with the DogTriathlonParticipant class and its test class. For
example, try the following:
 Add a new statement at the end of the TestDogs class that again
displays the data for any one of the participants. Note that as long as no
new objects are created, the cumulative score for all participants
remains the same no matter which participant uses it.
 Try to assign a value to the NUM_EVENTS constant from the display()
method, and then compile the class and read the error message
generated.
 Remove the keyword static from the definition of totalCumulativeScore
in the DogTriathlonParticipant class, and then recompile the classes
and run the program. Notice in the output that the nonstatic cumulative
score no longer reflects the cumulative score for all objects but only the
score for the current object using the display() method.
 Use 0 as the number of events for an object. When the participant’s
average is calculated, the result is not numeric, and NaN is displayed.
NaN is an acronym for Not a Number. In the next chapter, you will learn
to make decisions, and then you can prevent the NaN output.
Example on Page 220
As an example of how to use a GregorianCalendar object, Figure 4-37 shows
an
AgeCalculator application. In this class, a default GregorianCalendar object
named now is created. The user is prompted for a birth year, the current year
is extracted from the now object using the get() method, and the user’s age
this year is calculated by subtracting the birth year from the current year.
Figure 4-38 shows the output when a user born in 1986 runs the application in
2014.
Demonatrating the use of GregorianCalendar method – page 222
import java.util.*;
public class CalendarDemo
{
public static void main(String[] args)
{
GregorianCalendar now = new GregorianCalendar();
System.out.println("YEAR: " + now.get(Calendar.YEAR) );
System.out.println("MONTH: " + now.get(Calendar.MONTH));
System.out.println("WEEK_OF_YEAR: " +
now.get(Calendar.WEEK_OF_YEAR));
System.out.println("DATE: " + now.get(Calendar.DATE));
System.out.println("WEEK_OF_MONTH: " +
now.get(Calendar.WEEK_OF_MONTH));
System.out.println("DAY_OF_MONTH: " +
now.get(Calendar.DAY_OF_MONTH));
System.out.println("DAY_OF_YEAR: " +
now.get(Calendar.DAY_OF_YEAR));
System.out.println("DAY_OF_WEEK: " +
now.get(Calendar.DAY_OF_WEEK));
System.out.println("AM_PM: " + now.get(Calendar.AM_PM));
System.out.println("HOUR: " + now.get(Calendar.HOUR));
System.out.println("HOUR_OF_DAY: " +
now.get(Calendar.HOUR_OF_DAY));
System.out.println("MINUTE: " + now.get(Calendar.MINUTE));
System.out.println("SECOND: " + now.get(Calendar.SECOND));
System.out.println("MILLISECOND: " +
now.get(Calendar.MILLISECOND));
}
}
Worked example on page 249
import java.util.Scanner;
public class AssignVounteer
{
public static void main(String[] args)
{
int donationType;
String volunteer;
final int CLOTHING_CODE = 1;
final int OTHER_CODE = 2;
final String CLOTHING_PRICER = "Regina";
final String OTHER_PRICER = "Marco";
Scanner input = new Scanner(System.in);
System.out.println("What type of donation is this?");
System.out.print("Enter " + CLOTHING_CODE + " Clothing, " +
OTHER_CODE + " for anything else... ");
donationType = input.nextInt();
if(donationType == CLOTHING_CODE)
volunteer = CLOTHING_PRICER;
else
volunteer = OTHER_PRICER;
System.out.println("You entered " + donationType);
System.out.println("The volunteer who will price this item is " + volunteer);
}
}
Below is the output when the above code was ran with a selection of 1
On running the code with selection of 2
Example page 254
import java.util.Scanner;
public class AssignVounteer2
{
public static void main(String[] args)
{
int donationType;
String volunteer;
final int CLOTHING_CODE = 1;
final int OTHER_CODE = 2;
final String CLOTHING_PRICER = "Regina";
final String OTHER_PRICER = "Marco";
String message;
Scanner input = new Scanner(System.in);
System.out.println("What type of donation is this?");
System.out.print("Enter " + CLOTHING_CODE + " Clothing, " +
OTHER_CODE + " for anything else... ");
donationType = input.nextInt();
if(donationType == CLOTHING_CODE)
{
volunteer = CLOTHING_PRICER;
message = "clothing donation";
}
else
{
volunteer = OTHER_PRICER;
message = "another donation type";
}
System.out.println("This is " + message);
System.out.println("The volunteer who will price this item is " + volunteer);
}
}
The outputs obtained from running the above code with selection 1 and then 2
are shown below:
Example on page 259. The code above is modified to display the output below
when any code other than 1 or 2 are entered into the selection.
import java.util.Scanner;
public class AssignVounteer3
{
public static void main(String[] args)
{
int donationType;
String volunteer;
final int CLOTHING_CODE = 1;
final int OTHER_CODE = 2;
final String CLOTHING_PRICER = "Regina";
final String OTHER_PRICER = "Marco";
String message;
Scanner input = new Scanner(System.in);
System.out.println("What type of donation is this?");
System.out.print("Enter " + CLOTHING_CODE + " Clothing, " +
OTHER_CODE + " for anything else >>> ");
donationType = input.nextInt();
if(donationType == CLOTHING_CODE)
{
volunteer = CLOTHING_PRICER;
message = "clothing donation";
}
else
{
volunteer = OTHER_PRICER;
message = "another donation type";
}
if(donationType != CLOTHING_CODE)
if(donationType != OTHER_CODE)
{
volunteer = "INVALID.";
message = "an invalid donation type.";
}
System.out.println("This is " + message);
System.out.println("The volunteer who will price this item is " + volunteer);
}
}
Example on page 253
import java.util.Scanner;
public class Payroll
{
public static void main(String[] args)
{
double rate;
double hoursWorked;
double regularPay;
double overtimePay;
final int FULL_WEEK = 40;
final double OT_RATE = 1.5;
Scanner keyboard = new Scanner(System.in);
System.out.print("How many hours did you work this week? ");
hoursWorked = keyboard.nextDouble();
System.out.print("What is your regular pay rate? ");
rate = keyboard.nextDouble();
if(hoursWorked > FULL_WEEK)
{
regularPay = FULL_WEEK * rate;
overtimePay = (hoursWorked - FULL_WEEK) * OT_RATE * rate;
}
else
{
regularPay = hoursWorked * rate;
overtimePay = 0.0;
}
System.out.println("Regular pay is " +
regularPay + "nOvertime pay is " + overtimePay);
}
}
Java   small steps - 2019
Example on Page 274
import java.util.Scanner;
public class Assignment4 {
public static void main(String[] args) {
int donationType;
String volunteer;
final int CLOTHING_CODE = 1;
final int FURNITURE_CODE = 2;
final int ELECTRONICS_CODE = 3;
final int OTHER_CODE = 4;
final String CLOTHING_PRICER = "Regina";
final String OTHER_PRICER = "Marco";
final String FURNITURE_PRICER = "Walter";
final String ELECTRONICS_PRICER = "lydia";
String message;
Scanner input = new Scanner(System.in);
System.out.print("Enter an integer ...");
System.out.print("Enter " + CLOTHING_CODE + " Clothing, " +
OTHER_CODE + " for anything else >>> ");
donationType = input.nextInt();
switch (donationType) {
case (CLOTHING_CODE):
volunteer = CLOTHING_PRICER;
message = "a clothing donation";
break;
case (FURNITURE_CODE):
volunteer = FURNITURE_PRICER;
message = "a furniture donation";
break;
case (ELECTRONICS_CODE):
volunteer = ELECTRONICS_PRICER;
message = "an electronics donation";
break;
case (OTHER_CODE):
volunteer = OTHER_PRICER;
message = "another donation type";
break;
default:
volunteer = "invalid";
message = "an invalid donation type";
}
System.out.println("You entered " + donationType);
System.out.println("This is " + message);
System.out.println("The volunteer who will price this item is " + volunteer);
}
}
Page 291 Q1
1. Write an application that asks a user to enter an integer. Display a statement
that indicates whether the integer is even or odd. Save the file as EvenOdd.java.
C:UsersChristopherDocumentsNetBeansProjectsJDMay2018srcEvenOdd.java
import java.util.Scanner;
public class EvenOdd
{
public static void main(String[] args)
{
int num;
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter any number greater than 0:>> ");
num = keyboard.nextInt();
int number = num % 2;
if(number == 0)
{
System.out.println("This is an EVEN number");
}
else
System.out.println("This is an ODD number");
System.exit(0);
}
}
Page 291 Q2.
2. Write an application that prompts the user for the day’s high and low
temperatures. If the high is greater than or equal to 90 degrees, display the
message, “Heat warning.” If the low is less than 32 degrees, display the
message “Freeze warning.” If the difference between the high and low
temperatures is more than 40 degrees, display the message, “Large
temperature swing.” Save the file as Temperatures.java.
C:UsersChristopherDocumentsNetBeansProjectsJRVampedsrcTemperatures.java
import java.util.Scanner;
public class Temperatures
{
public static void main(String[] args)
{
double highTemp;
double lowTemp;
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter the day's high temperature. >>> ");
highTemp = keyboard.nextDouble();
System.out.print("Enter today's low temperature. >> ");
lowTemp = keyboard.nextDouble();
if (highTemp >= 90)
{
System.out.println("Heat warning");
}
else if (lowTemp <= 32)
{
System.out.println("Freeze warning");
}
if (highTemp - lowTemp > 40)
System.out.println("Large temperature swing");
}
}
3. a. Page 291
Write an application for the Summerdale Condo Sales office; the
program determines the price of a condominium. Ask the user to choose
1 for park view, 2 for golf course view, or 3 for lake view. The output is
the name of the chosen view as well as the price of the condo. Park view
condos are $150,000, condos with golf course views are $170,000, and
condos with lake views are $210,000. If the user enters an invalid code,
set the price to 0. Save the file as CondoSales.java.
C:UsersChristopherDocumentsNetBeansProjectsJRVampedsrcCondoSales.java
import java.util.Scanner;
public class CondoSales
{
public static void main(String[] args)
{
int condoCode;
final double PARK_VIEW_COST = 150000;
final double GOLF_COURSE_VIEW_COST = 170000;
final double LAKE_VIEW_COST = 210000;
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter the condo code: 1 for Park view; " +
"2 for Golf course view; 3 for Lake view. >>>");
condoCode = keyboard.nextInt();
switch (condoCode) {
case 1:
System.out.println("Park view condo costs: $" + PARK_VIEW_COST );
break;
case 2:
System.out.println("Golf Course view condo costs: $"
+ GOLF_COURSE_VIEW_COST);
break;
case 3:
System.out.println("Lake view condo costs: $" + LAKE_VIEW_COST);
break;
default:
System.out.print("Invalid code selected. ");
break;
}
}
}
Page 291 3b. Add a prompt to the CondoSales application to ask the user to
specify a (1) garage or a (2) parking space, but only if the condo view selection
is valid. Add $5,000 to the price of any condo with a garage. If the parking value
is invalid, display an appropriate message and assume that the price is for a
condo with no garage. Save the file as CondoSales2.java.
C:UsersChristopherDocumentsNetBeansProjectsJRVampedsrcCondoSales2.java
import java.util.Scanner;
public class CondoSales2
{
public static void main(String[] args)
{
int condoCode;
int spaceCode;
final double PARK_VIEW_COST = 150000;
final double GOLF_COURSE_VIEW_COST = 170000;
final double LAKE_VIEW_COST = 210000;
final double GARAGE_COST = 5000;
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter the condo code: 1 for Park view; " +
" 2 for Golf course view; 3 for Lake View. >>>");
condoCode = keyboard.nextInt();
System.out.println("Enter the parking space code: 1 for Garage; " +
"2 for Parking Space; >>>");
spaceCode = keyboard.nextInt();
if (((condoCode==1)||(condoCode==2)||(condoCode==3))
&& !(condoCode > 3) &&(spaceCode ==1))
{
switch (condoCode)
{
case 1:
System.out.println("Park view condo with garage costs: $" +
PARK_VIEW_COST + " + $" + GARAGE_COST + " for garage
space" );
break;
case 2:
System.out.println("Golf Course view condo with garage costs: $" +
GOLF_COURSE_VIEW_COST + " + $" + GARAGE_COST + " for
garage");
break;
case 3:
System.out.println("Lake view condo with garage costs $" +
LAKE_VIEW_COST + " + $" + GARAGE_COST + " for garage.");
break;
default:
System.out.print("Invalid code selected. ");
break;
}
}
else
if (spaceCode < 3)
{
switch (condoCode)
{
case 1:
System.out.println("Park view condo costs: $" + PARK_VIEW_COST );
break;
case 2:
System.out.println("Golf Course view condo costs: $" +
GOLF_COURSE_VIEW_COST);
break;
case 3:
System.out.println("Lake view condo costs: $" + LAKE_VIEW_COST);
break;
default:
System.out.print("INVALID Condo Code selected. ");
break;
}
}
else
System.out.println("INVALID Space Code selected");
}
}
4. a. The Williamsburg Women’s Club offers scholarships to local high school
students who meet any of several criteria. Write an application that prompts the
user for a student’s numeric high school grade point average (for example, 3.2),
the student’s number of extracurricular activities, and the student’s number of
service activities.
Display the message “Scholarship candidate” if the student has any of the
following:
 A grade point average of 3.8 or above and at least one extracurricular
activity and one service activity
 A grade point average below 3.8 but at least 3.4 and a total of at least
three extracurricular and service activities
 A grade point average below 3.4 but at least 3.0 and at least two
extracurricular
activities and three service activities
If the student does not meet any of the qualification criteria, display “Not a
candidate.” Save the file as Scholarship.java.
C:UsersChristopherDocumentsNetBeansProjectsJRVampedsrcScholarship.java
import java.util.Scanner;
public class Scholarship
{
public static void main(String[] args)
{
//declare string variable for holding message
String message;
//declare student's gpa as double
double gpa;
int extraCurr = 0;
int service = 0;
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter student's gpa. >> ");
gpa = keyboard.nextDouble();
System.out.print("Number of extra curricular activities: >> ");
extraCurr = keyboard.nextInt();
System.out.print("Number of other services: >> ");
service = keyboard.nextInt();
int activitySum = extraCurr + service;
// The logic below satisfies the first condition for scholarship
// (gpa >= 3.8)&&(extraCurr >= 1)&&(service >= 1)
// The logic below satisfies the second condition for scholarship
// (((!(gpa < 3.4))||(gpa < 3.8))&&(!(activitySum < 3)))
// The logic below satisfies the third condition for scholarship
// ((gpa >= 3)||(gpa < 3.4))&&(extraCurr >=2)&& (service >= 3)
// All the three conditions above are combined in the if statement
// below if the statement below executes to true => Scholarship
// if the statement executes to false => No Scholarship
if (((gpa >= 3.8)&&(extraCurr >= 1)&&(service >= 1))||(((!(gpa < 3.4))||
(gpa < 3.8))&&(!(activitySum < 3)))||(((((gpa >= 3)||(gpa < 3.4))&&
(extraCurr >=2))&& (service >= 3))))
message = "Scholarship Candidate. ";
else
message = "NOT a Scholarship candidate. ";
System.out.println(message);
System.exit(0);
}
}
4 b. Modify the Scholarship application so that if a user enters a grade
point average under 0 or over 4.0, or a negative value for either of the
activities, an error message appears. Save the file as Scholarship2.java
C:UsersChristopherDocumentsNetBeansProjectsJRVampedsrcScholarship2.java
import java.util.Scanner;
public class Scholarship2
{
public static void main(String[] args)
{
//declare string variable for holding message
String message;
//declare student's gpa as double
double gpa;
int extraCurr = 0;
int service = 0;
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter student's gpa. >> ");
gpa = keyboard.nextDouble();
System.out.print("Number of extra curricular activities: >> ");
extraCurr = keyboard.nextInt();
System.out.print("Number of other services: >> ");
service = keyboard.nextInt();
int activitySum = extraCurr + service;
// The logic below satisfies the first condition for scholarship
// (gpa >= 3.8) && (extraCurr >= 1) && (service >= 1)
// The logic below satisfies the second condition for scholarship
// (((!(gpa < 3.4)) || (gpa < 3.8)) && (!(activitySum < 3)))
// The logic below satisfies the third condition for scholarship
// ((gpa >= 3) || (gpa < 3.4)) && (extraCurr >=2) && (service >= 3)
// All the three conditions above are combined in the if statement below
// if the statement below executes to true => Scholarship
// if the statement executes to false => No Scholarship
if (((gpa >= 3.8) && (extraCurr >= 1) && (service >= 1)) || (((!(gpa < 3.4))
|| (gpa < 3.8)) && (!(activitySum < 3))) || (((((gpa >= 3) || (gpa < 3.4)) &&
(extraCurr >=2)) && (service >= 3))))
message = "Scholarship Candidate. ";
else
message = "NOT a Scholarship candidate. ";
//The next line checks if invalid parameters were entered.
if((gpa<0) || (gpa>4) || (service < 0) || (extraCurr < 0))
message = "Error!: Invalid values";
System.out.println(message);
System.exit(0);
}
}
Q5 page 292 (CODE NOT COMPLETED)
User should be able to make selection indefinitely till he wants to stop. But this
application stops working properly after second selection made by the user)
5. Write an application that displays a menu of three items for the Jivin’ Java
Coffee Shop as follows:
Prompt the user to choose an item using the number (1, 2, or 3) that
corresponds to the item, or to enter 0 to quit the application. After the user
makes the first selection, if the choice is 0, display a total bill of $0. Otherwise,
display the menu again. The user should respond to this prompt with another
item number to order or 0 to quit. If the user types 0, display the cost of the
single requested item. If the user types 1, 2, or 3, add the cost of the second
item to the first, and then display the menu a third time. If the user types 0 to
quit, display the total cost of the two items; otherwise, display the total for all
three selections. Save the file as Coffee.java.
Iteration 2
C:UsersChristopherDocumentsNetBeansProjectsJRVampedsrcCoffee.java
import java.util.Scanner;
public class Coffee
{
public static void main(String[] args)
{
int numSelected; //option selected 1, 2, 3 or 0
double orderCost = 0.0; //total value for ordered items
double americanCost = 1.99; //per unit cost American
double espressoCost = 2.50; //per unit cost espresso
double latteCost = 2.15; ////per unit cost latte
//the next lines instructs user to make selection
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter your order; 1 = American; 2 = Espresso; 3 = Latte; 0 =
Quit >> ");
numSelected = keyboard.nextInt();
if (numSelected == 0) //if user select 0, Total bill is displayed as $0.0 below
{
System.out.print("Add another item: 1 = American; 2 = Espresso; "
+ "3 = Latte; 0 = Quit >> ");
numSelected = keyboard.nextInt();
if(numSelected == 0)
System.out.print("Quit)");
System.exit(0);
}
else if (numSelected > 0)
{
switch(numSelected)
{
case 1:
orderCost = orderCost + americanCost;
break;
case 2:
orderCost = orderCost + espressoCost;
break;
case 3:
orderCost = orderCost + latteCost;
break;
default:
System.out.print("Invalid entry ");
System.out.println("Order Cost = " + orderCost);
}
System.out.print("Add another item: 1 = American; 2 = Espresso; "
+ "3 = Latte; 0 = Quit >> ");
numSelected = keyboard.nextInt();
if(numSelected == 0)
{
System.out.print("Quit)");
System.exit(0);
}
else if(numSelected >= 0)
{
switch(numSelected)
{
case 1:
orderCost = orderCost + americanCost;
break;
case 2:
orderCost = orderCost + espressoCost;
break;
case 3:
orderCost = orderCost + latteCost;
break;
default:
System.out.print("Invalid entry ");
}
System.out.println("Order Cost = " + orderCost);
System.out.print("Add another item: 1 = American; 2 = Espresso; "
+ "3 = Latte; 0 = Quit >> ");
numSelected = keyboard.nextInt();
if(numSelected == 0)
{
System.out.print("Quit)");
System.exit(0);
}
else if(numSelected >= 0)
{
switch(numSelected)
{
case 1:
orderCost = orderCost + americanCost;
break;
case 2:
orderCost = orderCost + espressoCost;
break;
case 3:
orderCost = orderCost + latteCost;
break;
default:
System.out.print("Invalid entry ");
}
System.out.println("Order Cost = " + orderCost);
System.out.print("Add another item: 1 = American; 2 = Espresso; "
+ "3 = Latte; 0 = Quit >> ");
numSelected = keyboard.nextInt();
if(numSelected == 0)
System.out.println("Order Cost = " + orderCost);
}
}
}
}
}
/*for non 0 selection, user is presented with the option of making additional
selections or quit. The app then display the cost for first selection or adds the cost of
first selection to the cost of second selection and display the total bill for the order
placed.
*/
SOLUTION (Iteration 1)
import java.util.Scanner;
public class Coffee
{
public static void main(String[] args)
{
int numSelected; //option selected 1, 2, 3 or 0
double orderCost = 0.0; //total value for ordered items
double americanCost = 1.99; //per unit cost American
double espressoCost = 2.50; //per unit cost espresso
double latteCost = 2.15; ////per unit cost latte
//the next lines instructs user to make selection
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter your order; 1 = American; 2 = Espresso; 3 = Latte; 0 =
Quit >> ");
numSelected = keyboard.nextInt();
if (numSelected == 0) //if user select 0, Total bill is displayed as $0.0 below
System.out.println("Total Bill = $0.00");
/*for non 0 selection, user is presented with
the option of making additional selections or quit.
The app then display the cost for first selection or
adds the cost of first selection to the cost of second
selection and display the total bill for the order placed.
*/
else
System.out.print("Add another item: 1 = American; 2 = Espresso; 3 = Latte; 0
= Quit >> ");
numSelected = keyboard.nextInt();
if (numSelected ==1)
{
if(numSelected == 0)
orderCost = americanCost;
if (numSelected == 1)
orderCost = 2 * americanCost;
if (numSelected == 2)
orderCost = americanCost + espressoCost;
if (numSelected == 3)
orderCost = americanCost + latteCost;
}
if (numSelected ==2)
{
if(numSelected == 0)
orderCost = espressoCost;
if (numSelected == 1)
orderCost = espressoCost + americanCost;
if (numSelected == 2)
orderCost = 2 * espressoCost;
//System.out.print("Total Bill is = $" + orderCost);
if (numSelected == 3)
orderCost = espressoCost + latteCost;
}
if (numSelected ==3)
{
if(numSelected == 0)
orderCost = latteCost;
if (numSelected == 1)
orderCost = latteCost + americanCost;
if (numSelected == 2)
orderCost = latteCost + espressoCost;
if (numSelected == 3)
orderCost = 2 * latteCost;
}
System.out.println("Add another item: Enter 1 for American, 2 for Espresso, 3
for Latte, Enter 0 to Quit >> ");
numSelected = keyboard.nextInt();
if (numSelected ==0)
System.out.println("Total Bill = $" + orderCost);
}
}
Q6 page 292
Barnhill Fastener Company runs a small factory. The company employs
workers who are paid one of three hourly rates depending on skill level:
Each factory worker might work any number of hours per week; any hours over 40
are paid at one and one-half times the usual rate. In addition, workers in skill levels 2
and 3 can elect the following insurance
options:
Also, workers in skill level 3 can elect to participate in the retirement plan at
3% of their gross pay. Write an interactive Java payroll application that
calculates the net pay for a factory worker. The program prompts the user for
skill level and hours worked, as well as appropriate insurance and retirement
options for the employee’s skill level category. The application displays: (1) the
hours worked, (2) the hourly pay rate, (3) the regular pay for 40 hours, (4) the
overtime pay, (5) the total of regular and overtime pay, and (6) the total
itemized deductions. If the deductions exceed the gross pay, display an error
message; otherwise, calculate and display (7) the net pay after all the
deductions have been subtracted from the gross. Save the file as Pay.java.
C:UsersChristopherDocumentsNetBeansProjectsJRVampedsrcPay.java
import java.util.Scanner;
public class Pay
{
public static void main(String[] args)
{
// Declare variables
int skillLevel;
int hoursWorked;
int insuranceOption;
int retirementOption;
double hourlyPayRate = 0.0;
final double LOW_PAY_RATE = 17.00;
final double MEDIUM_PAY_RATE = 20.00;
final double HIGH_PAY_RATE = 22.00;
//Insurance deduction for applicable workers
double insuranceRate;
double regularPay = 0;
double overTimePay = 0;
double totalPay = regularPay + overTimePay;
double insuranceCost = 0;
final double RETIREMENT_RATE = 0.03;
double retirementDeductions = 0; // Declared & initialized to 0
double totalDeductions = 0; // Declared & initialized to 0
double netPay = totalPay - insuranceCost;
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter skill level; 1, 2 or 3: >> ");
skillLevel = keyboard.nextInt();
System.out.print("Enter hours worked. >> ");
hoursWorked = keyboard.nextInt();
System.out.print("Enter insurance option. >> ");
insuranceOption = keyboard.nextInt();
System.out.print("Enter retirement option. >> ");
retirementOption = keyboard.nextInt();
// Calculating the net pay for Skill Level 1
// with hours worked <= 40.
if((skillLevel == 1) && (hoursWorked <= 40))
{
hourlyPayRate = LOW_PAY_RATE;
regularPay = hoursWorked * hourlyPayRate;
overTimePay = 0.0;
totalPay = regularPay + overTimePay;
insuranceCost = 0.00;
retirementDeductions = 0.00;
totalDeductions = insuranceCost + retirementDeductions;
netPay = totalPay - totalDeductions;
}
// Calculating Net Pay for SkillLevel 1 with
// hours worked > 40
if((skillLevel ==1) && (hoursWorked > 40))
{
hourlyPayRate = LOW_PAY_RATE;
regularPay = 40 * hourlyPayRate;
overTimePay = hourlyPayRate*(hoursWorked - 40)*1.5;
totalPay = regularPay + overTimePay;
insuranceCost = 0.00;
retirementDeductions = 0.00;
totalDeductions = insuranceCost + retirementDeductions;
netPay = totalPay - totalDeductions;
}
//Calculating the Net pay for Skill Level 2 with hours <= 40
if(skillLevel == 2)
{
if(hoursWorked <= 40)
{
hourlyPayRate = 20.00;
regularPay = hoursWorked * hourlyPayRate;
overTimePay = 0.00;
totalPay = regularPay + overTimePay;
switch(insuranceOption)
{
case 1:
insuranceCost = 32.50;
break;
case 2:
insuranceCost = 20.00;
break;
case 3:
insuranceCost = 10.00;
break;
default:
insuranceCost = 0.00;
}
retirementDeductions = 0.00;
totalDeductions = insuranceCost + retirementDeductions;
netPay = totalPay - totalDeductions;
}
}
//Calculating the Net pay for Skill Level 2 with hours > 40
if((skillLevel == 2) && (hoursWorked > 40))
{
hourlyPayRate = MEDIUM_PAY_RATE;
regularPay = 40 * hourlyPayRate;
overTimePay = 20.00*(hoursWorked - 40)*1.5;
totalPay = regularPay + overTimePay;
switch(insuranceOption)
{
case 1:
insuranceCost = 32.50;
break;
case 2:
insuranceCost = 20.00;
break;
case 3:
insuranceCost = 10.00;
break;
default:
insuranceCost = 0.00;
}
retirementDeductions = 0.00;
totalDeductions = insuranceCost + retirementDeductions;
netPay = totalPay - totalDeductions;
}
//Calculating the Net pay for Skill Level 3 with hours <= 40
if(skillLevel == 3)
{
if(hoursWorked <= 40)
{
hourlyPayRate = HIGH_PAY_RATE;
regularPay = hoursWorked * hourlyPayRate;
overTimePay = 0.00;
totalPay = regularPay + overTimePay;
switch(insuranceOption)
{
case 1:
insuranceCost = 32.50;
break;
case 2:
insuranceCost = 20.00;
break;
case 3:
insuranceCost = 10.00;
break;
default:
insuranceCost = 0.00;
}
totalDeductions = insuranceCost + retirementDeductions;
netPay = totalPay - totalDeductions;
if(retirementOption ==1)
retirementDeductions = 0.03 * netPay;
else
retirementDeductions = 0;
totalDeductions = insuranceCost + retirementDeductions;
netPay = totalPay - totalDeductions;
}
// Calculating the Net pay for Skill Level 3 with hours > 40
if(hoursWorked > 40)
{
hourlyPayRate = HIGH_PAY_RATE;
regularPay = 40 * hourlyPayRate;
overTimePay = 1.5*(hoursWorked - 40)*hourlyPayRate;
totalPay = regularPay + overTimePay;
switch(insuranceOption)
{
case 1:
insuranceCost = 32.50;
break;
case 2:
insuranceCost = 20.00;
break;
case 3:
insuranceCost = 10.00;
break;
default:
insuranceCost = 0.00;
}
totalDeductions = insuranceCost + retirementDeductions;
netPay = totalPay - totalDeductions;
if(retirementOption ==1)
retirementDeductions = 0.03 * netPay;
else
retirementDeductions = 0;
totalDeductions = insuranceCost + retirementDeductions;
netPay = totalPay - totalDeductions;
}
}
// If totalDeductions > totalPay, an error message is displayed.
if(totalDeductions > totalPay)
System.out.println("There is an Error !!! ");
else
//If totalDeductions < totalPay, the following items are displayed line by line.
{
System.out.println("Hours Worked = " + hoursWorked);
System.out.println("Hourly Pay Rate = " + hourlyPayRate);
System.out.println("Regular Pay = " + regularPay);
System.out.println("OverTime pay = " + overTimePay);
System.out.println("Gross Pay = " + totalPay);
System.out.println("Total Deductions = " + totalDeductions);
System.out.println("Net Pay = " + netPay);
}
}
}
7. Create a class for Shutterbug’s Camera Store, which is having a digital camera
sale. The class is named DigitalCamera, and it contains data fields for a brand, the
number of megapixels in the resolution, and price. Include a constructor that takes
arguments for the brand and megapixels. If the megapixel parameter is greater than
10, the constructor sets it to 10. The sale price is set based on the resolution; any
camera with 6 megapixels or fewer is $99, and all other cameras are $129. Also
include a method that displays DigitalCamera details. Write an application named
TestDigitalCamera in which you instantiate at least four objects, prompt the user for
values for the camera brand and number of megapixels, and display all the values.
Save the files as DigitalCamera.java and TestDigitalCamera.java.
C:UsersChristopherDocumentsNetBeansProjectsJRVampedsrcDigitalCamera.java
// DigitalCamera class that will be used to instantiate objects in
// TestDigitalCamera class.
public class DigitalCamera //name of class
{
private String brand; //data field parameter entered by user
private double mpixel; //data field parameter entered by user
private double price; //Price not set by user, depends on the megapixel.
//Write constructor that receives the brand and resolution parameters.
public DigitalCamera(String manuf, double resolution)
{
brand = manuf;
mpixel = resolution;
if (mpixel <= 6) // If Camera Mpix <= 6, price = $99
{
price = 99;
}
else
{
price = 129; // If camera Mpix > 6, price = $129
}
if (mpixel >= 10) // All cameras with resolution >= 10 have their Mpix
{ // treated as 10
mpixel = 10;
}
}
public String getBrand()
{
return brand;
}
public double getMpixel()
{
return mpixel;
}
public double getPrice()
{
return price;
}
public void setBrand(String manuf)
{
brand = manuf;
}
public void setMpixel(double resolution)
{
mpixel = resolution;
}
/* NOTE: Te set method is not needed in this app because it is
determined by the value of the megapixel parameter. But
the getPrice() is needed for other methods and instantiated
objects that need to use this method
public void setPrice(double amount)
{
price = amount;
}
*/
public void cameraDetails()
{
System.out.println("Camera brand: "+ brand );
System.out.println("Resolution: " + mpixel + " MP");
System.out.println("Sales Price: $" + price);
System.out.println("~~~~~~~~~~~~~~~");
}
}
C:UsersChristopherDocumentsNetBeansProjectsJRVampedsrcTestDigitalCamera.java
// TestDigitalCamera class
import java.util.Scanner;
public class TestDigitalCamera
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter 1st camera brand name: ");
String brand = keyboard.next();
System.out.print("Enter camera resolution in MP: ");
double mpixel = keyboard.nextDouble();
DigitalCamera canon = new DigitalCamera(brand, mpixel);
// brand = brand1.getBrand();
// mpixel = brand1.getMpixel();
// double price = brand1.getPrice();
System.out.println("");
canon.cameraDetails();
System.out.print("Enter 2nd camera brand name: ");
String brand1 = keyboard.next();
System.out.print("Enter camera resolution in MP: ");
double mpixel1 = keyboard.nextDouble();
DigitalCamera nikon = new DigitalCamera(brand1, mpixel1);
System.out.println("");
nikon.cameraDetails();
System.out.print("Enter 3rd camera brand name: ");
String brand2 = keyboard.next();
System.out.print("Enter camera resolution in MP: ");
double mpixel2 = keyboard.nextDouble();
DigitalCamera sony = new DigitalCamera(brand2, mpixel2);
System.out.println("");
sony.cameraDetails();
System.out.print("Enter 4th camera brand name: ");
String brand3 = keyboard.next();
System.out.print("Enter camera resolution in MP: ");
double mpixel3 = keyboard.nextDouble();
DigitalCamera olympus = new DigitalCamera(brand3, mpixel3);
System.out.println("");
olympus.cameraDetails();
}
}
Java   small steps - 2019
Q8, Page 293 (NOT COMPLETED: But you get the idea of what the solution
should look like and how to get to it at the end)
8. Create a class for the Parks Department in Cloverdale. The class is named
Park, and ito contains a String field for the name of the park, an integer field
for the size in acres, and four Boolean fields that hold whether the park has
each of
these features: picnic facilities, a tennis court, a playground, and a swimming
pool. Include get and set methods for each field. Include code in the method
that sets the number of acres and does not allow a negative number or a
number over 400. Save the file as Park.java. Then, create a program with
methods that do the following:
 Accepts a Park parameter and returns a Boolean value that indicates
whether the Park has both picnic facilities and a playground.
 Accepts a Park parameter and four Boolean parameters that represent
requests for the previously mentioned Park features. The method
returns true if the Park has all the requested features.
 Accepts a Park parameter and four Boolean parameters that represent
requests for the previously mentioned Park features. The method
returns true if the Park has exactly all the requested features and no
others.
 Accepts a Park parameter and returns the number of facilities that the
Park features.
 Accepts two Park parameters and returns the larger Park.
Declare at least three Park objects, and demonstrate that all the methods work
correctly. Save the program as TestPark.java.
// The NewPark class : Note the name has been changed from Park in
thabove question to NewPark
import java.util.Scanner;
public class NewPark
{
private String parkName;
private int parkAcres;
private boolean hasPicnic;
private boolean hasTennisCourt;
private boolean hasPlayground;
private boolean hasSwimming;
private boolean hasallfeatures;
public Scanner enter = new Scanner(System.in);
public void setParkName(String park)
{
parkName = park;
}
public void setParkAcres()
{
int acres;
String acresName;
System.out.println("Enter the number of acres for park: ");
acres = enter.nextInt();
if (acres < 0)
{
System.out.println("Acres is INVALID. Please enter a number greater than
0.");
setParkAcres();
}
else if (parkAcres > 400)
{
System.out.println("Acres is INVALID. Please enter a number less than 401.");
setParkAcres();
}
else
{
parkAcres = acres;
}
}
public void setHasPicnic()
{
int picnic;
System.out.println("Does park have picnic area?");
System.out.println("1 - YESn0 - NO");
picnic = enter.nextInt();
/*switch (picnic)
{
case 1:
picnic = 1;
hasPicnic = (1 > 0);
break;
case 2:
picnic = 0;
hasPicnic = (0 > 1);
break;
}*/
if (picnic == 1 )
{
hasPicnic = true;
}
else if(picnic == 0)
{
hasPicnic = false;
}
}
public void setHasTennisCourt()
{
int tennis;
System.out.println("Does park have a Tennis Court?");
System.out.println("1 - YESn0 - NO");
tennis = enter.nextInt();
switch (tennis)
{
case 1:
tennis = 1;
hasTennisCourt = (1 > 0);
break;
case 2:
tennis = 0;
hasTennisCourt = (0 > 1);
break;
}
}
public void setHasPlayground()
{
int playground;
System.out.println("Does park have a Playground?");
System.out.println("1 - YESn0 - NO");
playground = enter.nextInt();
switch (playground)
{
case 1:
playground = 1;
hasPlayground = (1 > 0);
break;
case 2:
playground = 0;
hasPlayground = (0 > 1);
break;
}
}
public void setHasSwimming()
{
int swimming;
System.out.println("Does park have a Swimming Pool?");
System.out.println("1 - YESn0 - NO");
swimming = enter.nextInt();
switch (swimming)
{
case 1:
swimming = 1;
hasSwimming = (1 > 0);
break;
case 2:
swimming = 0;
hasSwimming = (0 > 1);
break;
}
}
public void biggerPark(String fpark, String spark,int fi, int si)
{
if(fi > si)
{
System.out.println(fpark+" is bigger than "+spark);
}
else
{
System.out.println(spark+" is bigger than "+fpark);
}
}
public boolean hasallfeatures()
{
if (hasPicnic == hasTennisCourt == hasPlayground == hasSwimming == true)
{
return true;
}
else
return false;
}
public String getParkName()
{
return parkName;
}
public int getParkAcres()
{
return parkAcres;
}
public boolean getHasPicnic()
{
return hasPicnic;
}
public boolean getHasTennisCourt()
{
return hasTennisCourt;
}
public boolean getHasPlayground()
{
return hasPlayground;
}
public boolean getHasSwimming()
{
return hasSwimming;
}
public boolean getallfeatures()
{
return hasallfeatures;
}
}
//TestNewPark class
package MyJavaLab2;
import java.util.Scanner;
public class TestNewPark {
public static void main(String []args){
/*
Park first = new Park();
first.setHasPicnic();
first.setHasPlayground();
System.out.println(" Has picnic = "+first.getHasPicnic());
System.out.println(" Has playground = "+first.getHasPlayground());*/
//second question
NewPark second = new NewPark();
Scanner input = new Scanner(System.in);
System.out.println("ENTER PARK NAME");
String name = input.nextLine();
second.setParkName(name);
second.setParkAcres();
System.out.println(" the park name "+second.getParkName());
System.out.println("the park Acres is "+second.getParkAcres());
second.setHasPicnic();
second.setHasPlayground();
second.setHasSwimming();
second.setHasTennisCourt();
System.out.println("Does the park "+name+" have all the features?
"+second.hasallfeatures());
} }
Page 294, Q9
9. a. Create a class named Invoice that holds an invoice number, balance due, and three
fields representing the month, day, and year when the balance is due. Create a
constructor that accepts values for all five data fields. Within the constructor, assign each
argument to the appropriate field with the following exceptions:
l If an invoice number is less than 1000, force the invoice number to 0.
l If the month field is less than 1 or greater than 12, force the month field to 0.
l If the day field is less than 1 or greater than 31, force the day field to 0.
l If the year field is less than 2011 or greater than 2017, force the year field to 0.
In the Invoice class, include a display method that displays all the fields on an Invoice object.
Save the file as Invoice.java.
b. Write an application containing a main() method that declares several Invoice objects,
proving that all the statements in the constructor operate as specified. Save the file as
TestInvoice.java.
c. Modify the constructor in the Invoice class so that the day is not greater than 31, 30, or
28, depending on the month. For example, if a user tries to create an invoice for April 31,
force it to April 30. Also, if the month is invalid, and thus forced to 0, also force the day to
0. Save the modified Invoice class as Invoice2.java. Then modify the TestInvoice class to
create Invoice2 objects. Create enough objects to test every decision in the constructor.
Save this file as TestInvoice2.java.
//The Invoice class
package MyJavaLab2;
public class Invoice
{
private int InvoiceNumb;
private double BalanceDue;
private int Month;
private int Day;
private int Year;
Invoice(int invoice,double balanceDue,int year,int month,int day)
{
if (invoice <1000)
{
this.InvoiceNumb = 0;
}
else
{
this.InvoiceNumb = invoice;
}
this.BalanceDue = balanceDue;
if(year < 2011 || year > 2017)
{
this.Year = 0;
}
else
{
this.Year = year;
}
if (month < 1 || month > 12)
{
this.Month = 0;
}
else
{
this.Month = month;
}
if (day < 1 || day >31)
{
this.Day = 0;
}
else
{
this.Day = day;
}
}
/**
* @return the InvoiceNumb
*/
public int getInvoiceNumb()
{
return InvoiceNumb;
}
/**
* @param InvoiceNumb the InvoiceNumb to set
*/
public void setInvoiceNumb(int InvoiceNumb)
{
if (InvoiceNumb <1000)
{
this.InvoiceNumb = 0;
}
else
{
this.InvoiceNumb = InvoiceNumb;
}
}
/**
* @return the BalanceDue
*/
public double getBalanceDue()
{
return BalanceDue;
}
/**
* @param BalanceDue the BalanceDue to set
*/
public void setBalanceDue(double BalanceDue)
{
this.BalanceDue = BalanceDue;
}
/**
* @return the Month
*/
public int getMonth()
{
return Month;
}
/**
* @param Month the Month to set
*/
public void setMonth(int Month)
{
if (Month < 1 || Month > 12)
{
this.Month = 0;
}
{
this.Month = Month;
}
}
/**
* @return the Day
*/
public int getDay() {
return Day;
}
/**
* @param Day the Day to set
*/
public void setDay(int Day)
{
if (Day < 1 || Day >31)
{
this.Day = 0;
}
else
{
this.Day = Day;
}
}
/**
* @return the Year
*/
public int getYear() {
return Year;
}
/**
* @param Year the Year to set
*/
public void setYear(int Year)
{
if(Year < 2011 || Year > 2017)
{
this.Year = 0;
}
else
{
this.Year = Year;
}
}
public String ReturnValue()
{
System.out.println("Invoice number is: " + this.InvoiceNumb + " and the
balance due is: $" + this.BalanceDue);
System.out.println("YEAR: " + this.Year + " MONTH: " + this.Month + "
DAY: " + this.Day);
System.out.println();
return this.InvoiceNumb +" $"+this.BalanceDue+ " the year due is "
+this.Year +" the month is "+this.Month +" the day "+ this.Day;
}
}
//Test Invoice class
package MyJavaLab2;
import java.util.Scanner;
public class TestInvoice
{
public static void main(String []args)
{
Scanner input = new Scanner(System.in);
System.out.println("ENTER INVOICE NUMBER ");
int inviocenumb = input.nextInt();
System.out.println("ENTER BALANCE DUE ");
double balancdue = input.nextDouble();
System.out.println("ENTER THE YEAR ");
int year = input.nextInt();
System.out.println("ENTER THE MONTH ");
int month = input.nextInt();
System.out.println("ENTER THE DAY ");
int day = input.nextInt();
Invoice vice1 = new Invoice(inviocenumb,balancdue,year,month,day);
vice1.getInvoiceNumb();
vice1.getBalanceDue();
vice1.getYear();
vice1.getMonth();
vice1.getDay();
System.out.println(vice1.ReturnValue());
}}
Java   small steps - 2019
EXL1
Consider an application in which you ask the user for a bank balance and then
ask whether the user wants to see the balance after interest has accumulated.
Each time the user chooses to continue, an increased balance appears,
reflecting one more year of accumulated interest. When the user finally
chooses to exit, the program ends. The program output is as shown at the
end.
C:UsersChristopherDocumentsNetBeansProjectsJRVampedsrcBankBalance.java
import java.util.Scanner;
public class BankBalance
{
public static void main(String[] args)
{
double balance;
int response;
int year = 1;
final double INT_RATE = 0.03;
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter initial bank balance > ");
balance = keyboard.nextDouble();
System.out.println("Do you want to see next year's balance?");
System.out.print("Enter 1 for yes");
System.out.print(" or any other number for no >> ");
response = keyboard.nextInt();
while(response == 1)
{
balance = balance + balance * INT_RATE;
System.out.println("After year " + year + " at " + INT_RATE +
" interest rate, balance is $" + balance);
year = year + 1;
System.out.println("nDo you want to see the balance " +
"at the end of another year?");
System.out.print("Enter 1 for yes");
System.out.print(" or any other number for no >> ");
response = keyboard.nextInt();
}
}
}
EXL2 Suppose you want to display future bank balances while varying both
years and interest rates. Figure 6-24 shows an application that contains an
outer loop that varies interest rates between specified limits. At the start of the
outer loop, the working balance is reset to its initial value so that calculations
are correct for each revised interest rate value. The shaded inner loop varies
the number of years and displays each calculated balance. Figure 6-25 shows
a typical execution.
C:UsersChristopherDocumentsNetBeansProjectsJRVampedsrcBankBalanceByRateAndByYear.java
import java.util.Scanner;
public class BankBalanceByRateAndByYear
{
public static void main(String[]args)
{
double initialBalance;
double balance;
int year;
double interest;
final double LOW = 0.02;
final double HIGH = 0.05;
final double INCREMENT = 0.01;
final int MAX_YEAR = 4;
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter initial bank balance > ");
initialBalance = keyboard.nextDouble();
keyboard.nextLine();
for(interest = LOW; interest <= HIGH; interest += INCREMENT)
{
balance = initialBalance;
System.out.println("nWith an initial balance of $" + balance +
" at an interest of " + interest);
for(year = 1; year <= MAX_YEAR; ++ year)
{
balance = balance + balance*interest;
System.out.println("After year " + year + " balance is $" + balance);
}
}
}
}
Java   small steps - 2019
3. Write an application that displays the factorial for every integer value from 1
to 10. A factorial of a number is the product of that number multiplied by each
positive integer lower than it. For example, 4 factorial is 4 * 3 * 2 * 1, or 24.
Save the file as Factorials.java.
C:UsersChristopherDocumentsNetBeansProjectsJRVampedsrcFactorial.java
public class Factorial
{
public static void main(String[] args)
{
int n = 10;
int factorial = 1;
int i;
for(i=1; i<=n; ++i)
{
factorial = factorial * i;
System.out.println("Factorial of " + i + " is: " + factorial);
}
}
}
Page 342
1. a. Write an application that counts by five from 5 through 200 inclusive, and
that starts a new line after every multiple of 50 (50, 100, 150, and 200). Save
the file as CountByFives.java.
b. Modify the CountByFives application so that the user enters the value to
count by. Start each new line after 10 values have been displayed. Save the
file as CountByAnything.java.
C:UsersChristopherDocumentsNetBeansProjectsJRVampedsrcCountByFives.java
//This class counts un fives up to 200 and then display the results ten
// on each line. The results obtained in the output can also be varied
// by varying the value of the variable and the steps increment as needed.
public class CountByFives
{
public static void main(String[] args)
{
int val;
int count = 0;
final int GROUPT = 10;
for(val = 5; val <=211; val +=5)
{
count++;
if(count % GROUPT ==0)
{
System.out.println(val + " " );
}
else
{
System.out.print(val + " ");
}
}
}
}
/*The code for question 1b is as shown below. The code is tested as foloows.
The user wants to count in steps of 50 from 0 to any number say 1191 and
display the results 20 per line. These 3 values are entered in turn with
keyboard input.
*/
C:UsersChristopherDocumentsNetBeansProjectsJRVampedsrcCountByAnyThing.java
import java.util.Scanner;
public class CountByAnyThing
{
public static void main(String[] args)
{
int val; // the "INSTEPS OF" by which you want to count
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter the maximum range of the number:> ");
int value = keyboard.nextInt();
System.out.print("Enter the 'IN STEPS OF' by which you want to count:> ");
int steps = keyboard.nextInt();
System.out.print("Enter the 'IN GROUPS OF' by which you want " +
"the results displayed per line:> ");
int groupt = keyboard.nextInt();
System.out.println("");
int count = 0; // counter variable
for(val = steps; val <=value; val +=steps)
{
count++;
if(count % groupt ==0)
{
System.out.println(val + " " );
}
else
{
System.out.print(val + " ");
}
}
System.out.println("");
}
}
Page 342, Q2: Write an application that asks a user to type an even number to
continue or to type 999 to stop. When the user types an even number, display
the message “Good job!” and then ask for another input. When the user types
an odd number, display an error message and then ask for another input.
When the user types 999, end the program. Save the file as
EvenEntryLoop.java.
C:UsersChristopherDocumentsNetBeansProjectsJRVampedsrcEvenEntryLoop.java
import java.util.Scanner;
public class EvenEntryLoop
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter an EVEN number " +
"to continue or 999 to STOP:> ");
int entryValue = keyboard.nextInt();
while (entryValue != 999)
{
if (entryValue % 2 == 0)
{
System.out.print("Good job! ");
System.out.print("Enter an EVEN number to " +
"continue or 999 to STOP:> ");
entryValue = keyboard.nextInt();
}
else if(entryValue != 999)
{
System.out.print("Enter an EVEN number to " +
"continue or 999 to STOP:> ");
entryValue = keyboard.nextInt();
}
}
if (entryValue == 999)
{
System.out.print("PROGRAM ENDS" );
}
}
}
Java   small steps - 2019
Page 343, Q5. A knot is a unit of speed equal to one nautical mile per hour.
Write an application that displays every integer knot value from 15 through 30
and its kilometers per hour and miles per hour equivalents. One nautical mile
is 1.852 kilometers or 1.151 miles. Save the file as Knots.java.
C:UsersChristopherDocumentsNetBeansProjectsJRVampedsrcKnots.java
public class Knots
{
public static void main(String[] args)
{
int n = 15; // Maximum knots to conver
double kms;
double miles;
//1 knot = 1.852km
final double KM_FACTOR = 1.852;
// 1 knot = 1.151 miles
final double MILES_FACTOR = 1.1511;
int i;
System.out.println("Distances in knots & equivalents ");
System.out.println( "in km and miles n");
for(i=1; i<=n; ++i)
{
kms = i * KM_FACTOR;
miles = i * MILES_FACTOR;
System.out.println( + i + " knots, = " + kms +
(" kms; = ") + miles + " miles" );
}
}
}
Page 343. Q6. Write an application that shows the sum of 1 to n for every n from 1 to
50. That is, the program displays 1 (the sum of 1 alone), 3 (the sum of 1 and 2), 6 (the
sum of 1, 2, and 3), 10 (the sum of 1, 2, 3, and 4), and so on. Save the file as
EverySum.java.
//The following code gives the solution as a single line breaking through the screen.
C:UsersChristopherDocumentsNetBeansProjectsJRVampedsrcEverySum.java
public class EverySum
{
public static void main(String[] args)
{
int n;
int sum = 0;
for(n=1; n<=50; ++n)
{
sum = n + sum;
System.out.print(sum +", "); // Output runs down the of the screen
}
}
}
____________________________________________________
//The following code give the same output but with the resulting values
// displayed in groups of 20 per line
C:UsersChristopherDocumentsNetBeansProjectsJRVampedsrcEverySum2.java
public class EverySum2
{
public static void main(String[] args)
{
int n;
int sum = 0;
for(n=1; n<=50; ++n)
{
sum = n + sum;
if(n % 20 ==0)
{
System.out.println(sum + " " );
}
else
{
System.out.print(sum + " ");
}
}
}
}
Java   small steps - 2019
4. Write an application that prompts a user for two integers and displays every integer
between them. Display a message if there are no integers between the entered values. Make
sure the program works regardless of which entered value is larger. Save the file as
InBetween.java.
C:UsersChristopherDocumentsNetBeansProjectsJRVampedsrcInBetweenNumbers.java
import java.util.Scanner;
public class InBetweenNumbers
{
public static void main(String[] args)
{
int x, y; //Declare two integer variables
Scanner input = new Scanner(System.in);
System.out.print("Enter the first integer:>> ");
x = input.nextInt();
System.out.print("Enter the second integer:>> ");
y = input.nextInt();
System.out.println("The numbers inbetween " + x + " and " +y + " are; ");
if(x<y)
{
do
{
x = x+1;
System.out.print(x + " ");
}
while (x<(y-1));
}
else
if(x>y)
do
{
y = y+1;
System.out.print(y + " ");
}
while (y<(x-1));
}
}
Page 343, Question 9
9. Write an application that prompts a user for a child’s current age and the estimated
college costs for that child at age 18. Continue to reprompt a user who enters an age
value greater than 18. Display the amount that the user needs to save each year until
the child turns 18, assuming that no interest is earned on the money. For this
application, you can assume that integer division provides a sufficient answer. Save
the file as CollegeCost.java.
C:UsersChristopherDocumentsNetBeansProjectsJRVampedsrcCollegeCost.java
import java.util.Scanner;
public class CollegeCost
{
public static void main(String[] args)
{
int collegeCost; //College cost at age 18
int age; // child's curent age
final int ADDMISSION_AGE = 18;
int annualSavings; //Average annual savings
System.out.print("Enter college costs at age 18 year.> $");
Scanner input = new Scanner(System.in);
collegeCost = input.nextInt();
System.out.print("Enter child's current age in years. > " );
Scanner keyboard = new Scanner(System.in);
age = keyboard.nextInt();
while(age>18)
{
System.out.print("Please enter a valid age. >> ");
age = input.nextInt();
}
annualSavings = collegeCost/(ADDMISSION_AGE - age);
System.out.println("You must save $" + annualSavings + " each year.");
}
}
Page 344, Question 10
10. a. Write an application that prompts a user for the number of years the
user has until retirement and the amount of money the user can save annually.
If the user enters 0 or a negative number for either value, reprompt the user
until valid entries are made. Assume that no interest is earned on the money.
Display the amount of money the user will have at etirement. Save the file as
RetirementGoal.java.
C:UsersChristopherDocumentsNetBeansProjectsJRVampedsrcRetirementGoal.java
import java.util.Scanner;
public class RetirementGoal
{
public static void main(String[] args)
{
int yearsLeft;
double annualSavings;
double retirementSavings;
Scanner input = new Scanner(System.in);
System.out.print("Enter number of years before retirement:> ");
yearsLeft = input.nextInt();
while(yearsLeft<=0)
{
System.out.print("Please enter a valid number of years left.> ");
yearsLeft = input.nextInt();
}
System.out.print("Enter annual savings in $;> ");
annualSavings = input.nextDouble();
while(annualSavings<=0)
{
System.out.print("Please enter a value > 0 for your annual savings> ");
annualSavings = input.nextDouble();
}
retirementSavings = yearsLeft * annualSavings;
System.out.println("");
System.out.println("Retirement savings = $" + retirementSavings);
}
}
Page 433, Q1. Write an application that stores 12 integers in an array. Display
the integers from first to last, and then display the integers from last to first.
Save the file as TwelveInts.java.
package MyJavaLab3;
public class TwelveInts
{
public static void main(String[] args)
{
int[] twelveNums = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12};
int x;
System.out.print("The numbers in ascending order are: ");
for(x=0; x < twelveNums.length; ++x)
{
System.out.print(twelveNums[x] + ",");
}
System.out.println("");
System.out.println("");
System.out.print("The numbers in descending order are: ");
for(x= 0; x < twelveNums.length; ++x)
{
System.out.print(twelveNums[11-x] + ",");
}
System.out.println("");
}
}
C:UsersChristopherDocumentsNetBeansProjectsJRVampedsrcCompareStrings.java
// This example demonstrate how to compare strings
import java.util.Scanner;
public class CompareStrings
{
public static void main(String[] args)
{
String aName = "Carmen";
String anotherName;
Scanner input = new Scanner(System.in);
System.out.print("Enter your name > ");
anotherName = input.nextLine();
if(aName.equals(anotherName))
System.out.println(aName + " equals " + anotherName);
else
System.out.println(aName + " does not equal " + anotherName);
}
}
C:UsersChristopherDocumentsNetBeansProjectsJRVampedsrcBusinessLetter.java
/*
Tthe application prompts the user for a customer’s first and last names. The application then
extracts these names so that a friendly business letter can be constructed. After the application
prompts the user to enter a name, a loop control variable is initialized to 0. While the variable
remains less than the length of the entered name, each character is compared to the space
character. When a space is found, two new strings are created. The first, firstName, is the
substring of the original entry from position 0 to the location where the space was found. The
second, familyName, is the substring of the original entry from the position after the space to
the end of the string. Once the first and last names have been created, the loop control variable
is set to the length of the original string so the loop will exit and proceed to the display of the
friendly business letter.
*/
import javax.swing.*;
public class BusinessLetter
{
public static void main(String[] args)
{
String name;
String firstName = "";
String familyName = "";
int x;
char c;
name = JOptionPane.showInputDialog(null,
"Please enter customer's first and last name");
x = 0;
while(x < name.length())
{
if(name.charAt(x) == ' ')
{
firstName = name.substring(0, x);
familyName = name.substring(x + 1, name.length());
x = name.length();
}
++x;
}
JOptionPane.showMessageDialog(null,
"Dear " + firstName +
",nI am so glad we are on a first name basis" +
"nbecause I would like the opportunity to" +
"ntalk to you about an affordable insurance" +
"nprotection plan for the entire " + familyName +
"nfamily. Call A-One Family Insurance today" +
"nat 1-800-555-9287.");
}
}
Java   small steps - 2019
C:UsersChristopherDocumentsNetBeansProjectsJRVampedsrcRepairName.java
/*
Using String Methods
To demonstrate the use of the String methods, in this section you create an application that
asks a user for a name and then “fixes” the name so that the first letter of each new word is
uppercase, whether the user entered the name that way or not.
1. Open a new text file in your text editor. Enter the following first few lines of a RepairName
program. The program declares several variables, including two strings that will refer to a
name: one will be “repaired” with correct capitalization; the other will be saved as the user
entered it so it can be displayed in its original form at the end of the program. After declaring
the variables, prompt the user for a name:
*/
import javax.swing.*;
public class RepairName
{
public static void main(String[] args)
{
String name;
String saveOriginalName;
int stringLength;
int i;
char c;
name = JOptionPane.showInputDialog(null,
"Please enter your first and last name");
/*
2. Store the name entered in the saveOriginalName variable. Next, calculate the length of the
name the user entered, then begin a loop that will examine every character in the name. The
first character of a name is always capitalized, so when the loop control variable i is 0, the
character in that position in the name string is extracted and converted to its uppercase
equivalent. Then the name is replaced with the uppercase character appended to the
remainder of the existing name.
*/
saveOriginalName = name;
stringLength = name.length();
for(i = 0; i < stringLength; i++)
{
c = name.charAt(i);
if(i == 0)
{
c = Character.toUpperCase(c);
name = c + name.substring(1, stringLength);
}
/*
3. After the first character in the name is converted, the program looks through the rest of the
name, testing for spaces and capitalizing every character that follows a space. When a space
is found at position i, i is increased, the next character is extracted from the name, the
character is converted to its uppercase version, and a new name string is created using the old
string up to the current position, the newly capitalized letter, and the remainder of the name
string. The if…else ends and the for loop ends.
*/
else
if(name.charAt(i) == ' ')
{
++i;
c = name.charAt(i);
c = Character.toUpperCase(c);
name = name.substring(0, i) + c +
name.substring(i + 1, stringLength);
}
}
/*
4. After every character has been examined, display the original and repaired names, and add
closing braces for the main() method and the class.
*/
JOptionPane.showMessageDialog(null, "Original name was " +
saveOriginalName + "nRepaired name is " + name);
}
}
C:UsersChristopherDocumentsNetBeansProjectsJRVampedsrcNumberInput.java
/*
Converting a String to an Integer
In the next steps, you write a program that prompts the user for a number, reads characters
from the keyboard, stores the characters in a String, and then converts the String to an integer
that can be used in arithmetic statements.
1. Open a new text file in your text editor. Type the first few lines of a NumberInput class that
will accept string input:
*/
import javax.swing.*;
public class NumberInput
{
public static void main(String[] args)
{
/*
2. Declare the following variables for the input String, the integer to which it is converted, and
the result:
*/
String inputString;
int inputNumber;
int result;
/*
3. Declare a constant that holds a multiplier factor. This program will multiply the user’s input by
10:
*/
final int FACTOR = 10;
/*
4. Enter the following input dialog box statement that stores the user keyboard input in the
String variable inputString:
*/
inputString = JOptionPane.showInputDialog(null, "Enter a number");
/*
5. Use the following Integer.parseInt() method to convert the input String to an integer. Then
multiply the integer by 10 and display the result:
*/
inputNumber = Integer.parseInt(inputString);
result = inputNumber * FACTOR;
JOptionPane.showMessageDialog(null,
inputNumber + " * " + FACTOR + " = " + result);
/*
6. Add the final two closing curly braces for the program, then save the program as
NumberInput.java and compile and test the program. Figure 7-11 shows a typical execution.
Even though the user enters a String, it can be used successfully in an arithmetic statement
because it was converted using the parseInt() method.
*/
}
}
Java   small steps - 2019
C:UsersChristopherDocumentsNetBeansProjectsJRVampedsrcFindPrice.java
/*
Using Parallel Arrays : As an added bonus, if you set up another array with the same number
of elements and corresponding data, you can use the same subscript to access additional
information. A parallel array is one with the same number of elements as another, and for
which the values in corresponding elements are related. For example, if the 10 items your
company carries have 10 different prices, you can set up an array to hold those prices as
follows:
double[] prices = {0.29, 1.23, 3.50, 0.69…};
The prices must appear in the same order as their corresponding item numbers in the
validValues array. Now, the same for loop that finds the valid item number also finds the price,
as shown in the application in Figure 8-9. In the shaded portion of the code, notice that when
the ordered item’s number is found in the validValues array, the itemPrice value is “pulled” from
the prices array. In other words, if the item number is found in the second position in the
validValues array, you can find the correct price in the second position in the prices array.
Figure 8-10 shows a typical execution of the program. A user requests item 409, which is the
eighth element in the validValues array, so the price displayed is the eighth
element in the prices array.
*/
import javax.swing.*;
public class FindPrice
{
public static void main(String[] args)
{
final int NUMBER_OF_ITEMS = 10;
int[] validValues = {101, 108, 201, 213, 266, 304, 311, 409, 411, 412};
double[] prices = {0.29, 1.23, 3.50, 0.69, 6.79, 3.19, 0.99, 0.89, 1.26, 8.00};
String strItem;
int itemOrdered;
double itemPrice = 0.0;
boolean validItem = false;
strItem = JOptionPane.showInputDialog(null,
"Enter the item number you want to order");
itemOrdered = Integer.parseInt(strItem);
for(int x = 0; x < NUMBER_OF_ITEMS; ++x)
{
if(itemOrdered == validValues[x])
{
validItem = true;
itemPrice = prices[x];
}
}
if(validItem)
JOptionPane.showMessageDialog(null, "The price for item "
+ itemOrdered + " is $" + itemPrice);
else
JOptionPane.showMessageDialog(null,
"Sorry - invalid item entered");
}
}
Java   small steps - 2019
As an example of how useful two-dimensional arrays can be, assume that you own an apartment
building with four floors—a basement, which you refer to as floor zero, and three other floors
numbered one, two, and three. In addition, each of the floors has studio (with no bedroom) and one-
and two-bedroom apartments. The monthly rent for each type of apartment is different—the higher
the floor, the higher the rent (the view is better), and the rent is higher for apartments with more
bedrooms. Table 9-1 shows the rental amounts.
To determine a tenant’s rent, you need to know two pieces of information: the floor on which the
tenant rents an apartment and the number of bedrooms in the apartment. Within a Java program,
you can declare an array of rents using the following code:
int[][] rents = {{400, 450, 510},
{500, 560, 630},
{625, 676, 740},
{1000, 1250, 1600}};
If you declare two integers named floor and bedrooms, then any tenant’s rent can be referred to as
rents[floor][bedrooms]. Figure 9-10 shows an application that prompts a user for a floor number and
number of bedrooms. A typical execution follows next.
C:UsersChristopherDocumentsNetBeansProjectsJDMay2018srcFindRent.java
import javax.swing.*;
class FindRent
{
public static void main(String[] args)
{
int[][] rents = { {400, 450, 510},
{500, 560, 630},
{625, 676, 740},
{1000, 1250, 1600} };
String entry;
int floor;
int bedrooms;
entry = JOptionPane.showInputDialog(null, "Enter a floor number ");
floor = Integer.parseInt(entry);
entry = JOptionPane.showInputDialog(null, "Enter number of bedrooms ");
bedrooms = Integer.parseInt(entry);
JOptionPane.showMessageDialog(null, "The rent for a " + bedrooms +
" bedroom apartment on floor " + floor + " is $" + rents[floor][bedrooms]);
}
}
Below is an application that uses the length fields associated with the rents array to display all
the rents. The floor variable varies from 0 through one less than 4 in the outer loop, and the
bdrms variable varies from 0 through one less than 3 in the inner loop. The output is shown
next.
C:UsersChristopherDocumentsNetBeansProjectsJDMay2018srcDisplayRents.java
class DisplayRents
{
public static void main(String[] args)
{
int[][] rents = { {400, 450, 510},
{500, 560, 630},
{625, 676, 740},
{1000, 1250, 1600} };
int floor;
int bdrms;
for(floor = 0; floor < rents.length; ++floor)
for(bdrms = 0; bdrms < rents[floor].length; ++bdrms)
System.out.println("Floor " + floor + " Bedrooms " +
bdrms + " Rent is $" + rents[floor][bdrms]);
}
}
Java   small steps - 2019
You can declare an enumerated type in its own file, in which case the filename matches the
type name and has a .java extension. You will use this approach in a “You Do It” exercise later
in this chapter. Alternatively, you can declare an enumerated type within a class, but not within
a method. Figure 9-24 is an application that declares a Month enumeration and demonstrates
its use. Figure 9-25 shows two typical executions.
C:UsersChristopherDocumentsNetBeansProjectsJRVampedsrcEnumDemo.java
import java.util.Scanner;
public class EnumDemo
{
enum Month {JAN, FEB, MAR, APR, MAY, JUN,
JUL, AUG, SEP, OCT, NOV, DEC};
public static void main(String[] args)
{
Month birthMonth;
String userEntry;
int position;
int comparison;
Scanner input = new Scanner(System.in);
System.out.println("The months are:");
for(Month mon : Month.values())
System.out.print(mon + " ");
System.out.print("nnEnter the first three letters of " +
"your birth month >> ");
userEntry = input.nextLine().toUpperCase();
birthMonth = Month.valueOf(userEntry);
System.out.println("You entered " + birthMonth);
position = birthMonth.ordinal();
System.out.println(birthMonth + " is in position " + position);
System.out.println("So its month number is " + (position + 1));
comparison = birthMonth.compareTo(Month.JUN);
if(comparison < 0)
System.out.println(birthMonth + " is earlier in the year than " + Month.JUN);
else
if(comparison > 0)
System.out.println(birthMonth + " is later in the year than " + Month.JUN);
else
System.out.println(birthMonth + " is " + Month.JUN);
}
}
Java   small steps - 2019
You can use enumerations to control a switch structure. Figure 9-26 contains a class that
declares a Property enumeration for a real estate company. The program assigns one of the
values to a Property variable and then uses a switch structure to display an appropriate
message. Figure 9-27 shows the result.
C:UsersChristopherDocumentsNetBeansProjectsJRVampedsrcEnumDemo2.java
import java.util.Scanner;
public class EnumDemo2
{
enum Property {SINGLE_FAMILY, MULTIPLE_FAMILY,
CONDOMINIUM, LAND, BUSINESS};
public static void main(String[] args)
{
Property propForSale = Property.MULTIPLE_FAMILY;
switch(propForSale)
{
case SINGLE_FAMILY:
case MULTIPLE_FAMILY:
System.out.println("Listing fee is 5%");
break;
case CONDOMINIUM:
System.out.println("Listing fee is 6%");
break;
case LAND:
case BUSINESS:
System.out.println
("We do not handle this type of property");
}
}
}
Creating an enumeration type provides you with several advantages. For example, the Month
enumeration improves your programs in the following ways:
 If you did not create an enumerated type for month values, you could use another
type— for example, ints or Strings. The problem is that any value could be assigned to
an int or String variable, but only the 12 allowed values can be assigned to a Month.
 If you did not create an enumerated type for month values, you could create another
type to represent months, but invalid behavior could be applied to the values. For
example, if you used integers to represent months, you could add, subtract, multiply, or
divide two months, which is not logical. Programmers say using enums makes the
values type-safe. Type-safe describes a data type for which only appropriate behaviors
are allowed.
 The enum constants provide a form of self-documentation. Someone reading your
program might misinterpret what 9 means as a month value, but there is less confusion
when you use the identifier OCT.
 As with other classes, you can also add methods and other fields to an enum type.
Using Part of an Array
Sometimes, you do not want to use every value in an array. For example, suppose that you
write a program that allows a student to enter up to 10 quiz scores and then computes and
displays the average. To allow for 10 quiz scores, you create an array that can hold 10 values,
but because the student might enter fewer than 10 values, you might use only part of the array.
The code below shows such a program.
C:UsersChristopherDocumentsNetBeansProjectsJRVampedsrcFlexibleQuizAverage.java
import java.util.*;
public class AverageOfQuizzes
{
public static void main(String[] args)
{
int[] scores = new int[10];
int score = 0;
int count = 0;
int total = 0;
final int QUIT = 999;
final int MAX = 10;
Scanner input = new Scanner(System.in);
System.out.print("Enter quiz score or " + QUIT + " to quit >> ");
score = input.nextInt();
while(score != QUIT)
{
scores[count] = score;
total += scores[count];
++count;
if(count == MAX)
score = QUIT;
else
{
System.out.print("Enter next quiz score or " + QUIT + " to quit >> ");
score = input.nextInt();
}
}
System.out.print("nThe scores entered were: ");
for(int x = 0; x < count; ++x)
System.out.print(scores[x] + " ");
if(count != 0)
System.out.println("n The average is " + (total * 1.0 / count));
else
System.out.println("No scores were entered.");
}
}
Java   small steps - 2019
Ch9; EX1; Page 446
Using a Bubble Sort
In this section, you create a program in which you enter values that you sort
using the bubble sort algorithm. You display the values during each iteration of
the outer sorting loop so that you can track the values as they are repositioned
in the array.
package MyJavaLab4;
import java.util.Scanner;
class BubbleSortDemo
{
public static void main(String[] args)
/*
Declare an array of 5 integers and a variable to control the number
of comparissons to make during the sort. Declare a Scanner object,
two integers to use as subscripts for handling the array, and a temporary
integer value to use during the sort.
*/
{
int[] someNums = new int[5];
int comparisonsToMake = someNums.length - 1;
Scanner keyboard = new Scanner(System.in);
int a, b, temp;
/*
Next is a for loop that prompts user for a
value for each array element and accepts them.
*/
for(a = 0; a < someNums.length; ++a)
{
System.out.print("Enter number " + (a + 1) + " >> ");
someNums[a] = keyboard.nextInt();
}
/*
Next, call a method that accepts the array and the number of sort
iterations performed so far, which is 0. The purpose of the method
is to display the current status of the array as it is being sorted.
*/
display(someNums, 0);
/*
Add the nested loops that perform the sort. The outer loop controls
the number of passes through the list, and the inner loop controls the
comparisons on each pass through the list. When any two adjacent
elements
are out of order, they are swapped. At the end of the nested loop, the
current
list is output and the number of comparisons to be made on the next pass
is
reduced by one.
*/
for(a = 0; a <someNums.length -1; ++a)
{
for(b = 0; b < comparisonsToMake; ++b)
{
if(someNums[b] > someNums[b+1])
{
temp = someNums[b];
someNums[b] =someNums[b+1];
someNums[b+1] = temp;
}
}
display(someNums, (a+1));
--comparisonsToMake;
}
/*
After the closing brace for the main() method, but before the closing
brace for the class, insert the display() method. It accepts the array
and the current outer loop index, and it displays the array contents.
*/
}
public static void display(int[] someNums, int a)
{
System.out.print("Iteration "+ a + "; ");
for(int x = 0; x < someNums.length; ++x)
System.out.print(someNums[x] + " ");
System.out.println();
}
/*
Notice that after the first iteration, the largest value
has sunk to the bottom of the list. After the second iteration,
the two largest values are at the bottom of the list, and so on.
*/
}
The previous lines of code are now modified so that the user can enter
an array of any length for sorting. First, the user indicate the length, i, of
the array from the beginning. The implementation was demonstrated
with an array length of 9 elements. The line of codes that specify the
array length is highlighted in blue.
package MyJavaLab4;
import java.util.Scanner;
class BubbleSortDemo
{
public static void main(String[] args)
/*
Declare an array of 5 integers and a variable to control the number
of comparissons to make during the sort. Declare a Scanner object,
two integers to use as subscripts for handling the array, and a temporary
integer value to use during the sort.
*/
{
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter the length of the array, i = ");
int i = keyboard.nextInt();
int[] someNums = new int[i];
int comparisonsToMake = someNums.length - 1;
int a, b, temp;
/*
Next is a for loop that prompts user for a
value for each array element and accepts them.
*/
for(a = 0; a < someNums.length; ++a)
{
System.out.print("Enter number " + (a + 1) + " >> ");
someNums[a] = keyboard.nextInt();
}
/*
Next, call a method that accepts the array and the number of sort
iterations performed so far, which is 0. The purpose of the method
is to display the current status of the array as it is being sorted.
*/
display(someNums, 0);
/*
Add the nested loops that perform the sort. The outer loop controls
the number of passes through the list, and the inner loop controls the
comparisons on each pass through the list. When any two adjacent
elements
are out of order, they are swapped. At the end of the nested loop, the
current
list is output and the number of comparisons to be made on the next pass
is
reduced by one.
*/
for(a = 0; a <someNums.length -1; ++a)
{
for(b = 0; b < comparisonsToMake; ++b)
{
if(someNums[b] > someNums[b+1])
{
temp = someNums[b];
someNums[b] =someNums[b+1];
someNums[b+1] = temp;
}
}
display(someNums, (a+1));
--comparisonsToMake;
}
/*
After the closing brace for the main() method, but before the closing
brace for the class, insert the display() method. It accepts the array
and the current outer loop index, and it displays the array contents.
*/
}
public static void display(int[] someNums, int a)
{
System.out.print("Iteration "+ a + "; ");
for(int x = 0; x < someNums.length; ++x)
System.out.print(someNums[x] + " ");
System.out.println();
}
/*
Notice that after the first iteration, the largest value
has sunk to the bottom of the list. After the second iteration,
the two largest values are at the bottom of the list, and so on.
*/
}
EXAMPLE demonstrating the creation of a Superclass and an application to use
it page 498
//Party Class
C:UsersChristopherDocumentsNetBeansProjectsJRVampedsrcParty.java
public class Party
{
private int guests; // private field
// public get and set methods
public int getGuests()
{
return guests;
}
public void setGuests(int numGuests)
{
guests = numGuests;
}
// Method that displays a party invitation
public void displayInvitation()
{
System.out.println("Please come to my party! ");
}
}
//Writig an Application that uses the Party class : UseParty.java
C:UsersChristopherDocumentsNetBeansProjectsJRVampedsrcUseParty.java
import java.util.Scanner;
public class UseParty
{
public static void main(String[] args)
{
// Declare variables for the number of guests, a Party objects
// and a Scanner object for user input.
int guests;
Party aParty = new Party();
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter the number of guests for the party:> ");
guests = keyboard.nextInt();
aParty.setGuests(guests);
System.out.println("The party has " + aParty.getGuests() + " guests.");
aParty.displayInvitation();
}
}
//Creating a Subclass from the Party class: DinnerParty.java
C:UsersChristopherDocumentsNetBeansProjectsJRVampedsrcDinnerParty.java
public class DinnerParty extends Party
{
// private field particular to DinnerParty class
// The other fields are already defined in the Party class
private int dinnerChoice;
// get and set methods for dinnerChoice field
public int getDinnerChoice()
{
return dinnerChoice;
}
public void setDinnerChoice(int choice)
{
dinnerChoice = choice;
}
}
//Creating an Application that uses the DinnerParty class; UseDinnerParty.java
C:UsersChristopherDocumentsNetBeansProjectsJRVampedsrcUseDinnerParty.java
import java.util.Scanner;
public class UseDinnerParty
{
public static void main(String[] args)
{
// Declare variables for the number of guests, a Party objects
// and a Scanner object for user input.
int guests;
int choice;
Party aParty = new Party();
DinnerParty aDinnerParty = new DinnerParty();
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter the number of guests for the party:> ");
guests = keyboard.nextInt();
aParty.setGuests(guests);
System.out.println("The party has " + aParty.getGuests() + " guests.");
aParty.displayInvitation();
System.out.print("nEnter the number of guests for the dinner party:> ");
guests = keyboard.nextInt();
aDinnerParty.setGuests(guests);
System.out.print("Enter the menu option --- 1 for chicken and 2 for beef:>n ");
choice = keyboard.nextInt();
aDinnerParty.setDinnerChoice(choice);
System.out.println("The dinner party has " + aDinnerParty.getGuests() + " guests.");
System.out.println("Menu option " + aDinnerParty.getDinnerChoice() + " will be served. ");
aDinnerParty.displayInvitation();
}
}
Exception Handling Examples
C:UsersChristopherDocumentsNetBeansProjectsJRVampedsrcDivisionMistakeCaught.java
/*
The main() method in the class contains a try block with code
that attempts division.When illegal integer division is attempted,
an ArithmeticException is automatically created and the catch
block executes.
*/
import java.util.Scanner;
public class DivisionMistakeCaught
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int numerator, denominator, result;
System.out.print("Enter numerator:>> ");
numerator = input.nextInt();
System.out.print("Enter denomiator:>> ");
denominator = input.nextInt();
try
{
result = numerator / denominator;
System.out.println(numerator + " / " +
denominator + " = " + result);
}
catch(ArithmeticException mistake)
{
System.out.print(mistake.getMessage());
}
System.out.println(" End of program");
}
}
C:UsersChristopherDocumentsNetBeansProjectsJRVampedsrcEnteringIntegers.java
/*
to add a nextLine() call after any next(), nextInt(), or nextDouble() call to absorb the Enter key
remaining in the input buffer before subsequent nextLine() calls. When you attempt to convert
numeric data in a try block and the effort is followed by another attempted conversion, you also
must remember to account for the potential remaining characters left in the input buffer. This
program accepts and displays an array of six integers.
*/
import java.util.Scanner;
public class EnteringIntegers
{
public static void main(String[] args)
{
int[] numberList = {0, 0, 0, 0, 0, 0};
int x;
Scanner input = new Scanner(System.in);
for(x = 0; x < numberList.length; ++x)
{
try
{
System.out.print("Enter an integer >>: ");
numberList[x] = input.nextInt();
}
catch(Exception e)
{
System.out.println("Exception occured");
}
// input.nextLine();
// After the first run, uncomment the above
// line & re-run. Notice how the program responds
}
System.out.print("The numbers are: ");
for(x = 0; x < numberList.length; ++x)
System.out.print(numberList[x] + " " );
System.out.println(" ");
}
}
Throwing and Catching Multiple Exceptions
You can place as many statements as you need within a try block, and you can catch as many exceptions as
you want. If you try more than one statement, only the first error-generating statement throws an exception.
As soon as the exception occurs, the logic transfers to the catch block, which leaves the rest of the
statements in the try block unexecuted.
When a program contains multiple catch blocks, they are examined in sequence until a match is found for
the type of exception that occurred. Then, the matching catch block executes, and each remaining catch
block is bypassed. For example, consider the application in Figure 12-18. The main() method in the
DivisionMistakeCaught3 class throws two types of Exception objects: an ArithmeticException and an
InputMismatchException. The try block in the application surrounds all the statements in which the
exceptions might occur.
C:UsersChristopherDocumentsNetBeansProjectsJRVampedsrcDivisionMistakeCaught3.java
import java.util.*;
public class DivisionMistakeCaught3
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int numerator, denominator, result;
try
{
System.out.print("Enter numerator >> ");
numerator = input.nextInt();
System.out.print("Enter denominator >> ");
denominator = input.nextInt();
result = numerator / denominator;
System.out.println(numerator + " / " + denominator +
" = " + result);
}
catch(ArithmeticException mistake)
{
System.out.println(mistake.getMessage());
}
catch(InputMismatchException mistake)
{
System.out.println("Wrong data type");
}
System.out.println("End of program");
}
}
Java   small steps - 2019
/* INCLUDING JCheckBoxes in an Application – page 776
Create an interactive program for a resort. The base price for a room is $200,
and a guest can choose from several options. Reserving a room for a
weekend night adds $100 to the price, including breakfast adds $20, and
including a round of golf adds $75. A guest can select none, some, or all of
these premium additions. Each time the user changes the option package, the
price is recalculated.
1. Open a new file, and then type the following first few lines of a Swing
application that demonstrates the use of a JCheckBox. Note that the
JResortCalculator class implements the ItemListener interface:
*/
package MyGUIx;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class JResortCalculator extends JFrame implements ItemListener
{
/* 2. Declare the named constants that hold the base price for a resort room
and
the premium amounts for a weekend stay, including breakfast and a round of
golf. Also include a variable that holds the total price for the stay, and initialize
it to the value of the base price. Later, depending on the user’s selections,
premium fees might be added to totalPrice, making it more than
BASE_PRICE.
*/
final int BASE_PRICE = 200;
final int WEEKEND_PREMIUM = 100;
final int BREAKFAST_PREMIUM = 20;
final int GOLF_PREMIUM = 75;
int totalPrice = BASE_PRICE;
/* 3. Declare three JCheckBox objects. Each is labeled with a String that
contains
a description of the option and the cost of the option. Each JCheckBox starts
unchecked or deselected.
*/
JCheckBox weekendBox = new JCheckBox("Weekend premium $" +
WEEKEND_PREMIUM, false);
JCheckBox breakfastBox = new JCheckBox("Breakfast $" +
BREAKFAST_PREMIUM, false);
JCheckBox golfBox = new JCheckBox("Golf $" + GOLF_PREMIUM, false);
/* 4. Include JLabels to hold user instructions and information and a JTextField
in
which to display the total price:
*/
JLabel resortLabel = new JLabel("Resort Price Calculator");
JLabel priceLabel = new JLabel("The price for your stay is");
JTextField totPrice = new JTextField(4);
JLabel optionExplainLabel = new JLabel("Base price for a room is $" +
BASE_PRICE + ".");
JLabel optionExplainLabel2 = new JLabel("Check the options you want");
/* 5. Begin the JResortCalculator class constructor. Include instructions to set
the title by passing it to the JFrame parent class constructor, to set the default
close operation, and to set the layout manager. Then add all the necessary
components to the JFrame.
*/
public JResortCalculator()
{
super("Resort Price Calculator");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new FlowLayout());
add(resortLabel);
add(optionExplainLabel);
add(optionExplainLabel2);
add(weekendBox);
add(breakfastBox);
add(golfBox);
add(priceLabel);
add(totPrice);
/* 6. Continue the constructor by setting the text of the totPrice JTextField to
display a dollar sign and the totalPrice value. Register the class as a listener
for events generated by each of the three JCheckBoxes. Finally, add a closing
curly brace for the constructor.
*/
totPrice.setText("$" + totalPrice);
weekendBox.addItemListener(this);
breakfastBox.addItemListener(this);
golfBox.addItemListener(this);
}
/* 7. Begin the itemStateChanged() method that executes when the user
selects
or deselects a JCheckBox. Use the appropriate methods to determine
which JCheckBox is the source of the current ItemEvent and whether the
event was generated by selecting a JCheckBox or by deselecting one.
*/
@Override
public void itemStateChanged(ItemEvent event)
{
Object source = event.getSource();
int select = event.getStateChange();
/* 8. Write a nested if statement that tests whether the source is equivalent to
the
weekendBox, breakfastBox, or, by default, the golfBox. In each case,
depending on whether the item was selected or deselected, add or subtract
the corresponding premium fee from the totalPrice. Display the total price
in the JTextField, and add a closing curly brace for the method.
*/
if(source == weekendBox)
if(select ==ItemEvent.SELECTED)
totalPrice += WEEKEND_PREMIUM;
else
totalPrice -= WEEKEND_PREMIUM;
else if(source == breakfastBox)
{
if(select == ItemEvent.SELECTED)
totalPrice += BREAKFAST_PREMIUM;
else
totalPrice -= BREAKFAST_PREMIUM;
}
else//if(source == golfBox) by default
if(select == ItemEvent.SELECTED)
totalPrice += GOLF_PREMIUM;
else
totalPrice -= GOLF_PREMIUM;
totPrice.setText("$" + totalPrice);
}
/* 9. Add a main() method that creates an instance of the JFrame and sets its
size
and visibility. Then add a closing curly brace for the class.
*/
public static void main(String[] args)
{
JResortCalculator aFrame = new JResortCalculator();
final int WIDTH = 300;
final int HEIGHT = 200;
aFrame.setSize(WIDTH, HEIGHT);
aFrame.setVisible(true);
}
}
/* 10. Save the file as JResortCalculator.java. Compile and execute the
application. The output appears in Figure 14-41 with the base price initially
set to $200.
*/
Java   small steps - 2019
Scene Builder Example (Gaddis page 998 – 1016)
Summary of Creating a JavaFX Application
Here is a broad summary of the steps that you take when creating a JavaFX
application
 Use Scene Builder to design the GUI. Be sure to give an fx:id to all of the
components that you plan to access in your Java code. Save the GUI as an
FXML file.
 Write the code for the main application class, which loads the FXML file and
launches the application. Save and compile the code in the same location as the
FXML file.
 Write the code for the controller class, which contains the event handler
methods for the GUI. Save and compile the code in the same location as the
FXML file.s
 In Scene Builder, register the controller class, then register an event handler
method for each component that needs to respond to events. Save the FXML
file again.
NOTE: All the the 3 files must be in the same folder.
KiloConverter.fxml (Created in Scene Builder. To open in NetBeans, right click and
select edit.)
KiloConverterController.java
KiloCnntroller.java (The main program)
KiloConverter.fxml file
C:UsersChristopherDocumentsNetBeansProjectsJavaOPS_2019srcKilo
meterConverter.fxml
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.control.*?>
<?import java.lang.*?>
<?import javafx.scene.layout.*?>
<AnchorPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity"
minWidth="-Infinity" prefHeight="206.0" prefWidth="467.0"
xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1"
fx:controller="KilometerConverterController">
<children>
<Label fx:id="promptLabel" layoutX="35.0" layoutY="53.0" text="Enter a
distance in kilometers" />
<TextField fx:id="kilometerTextField" layoutX="336.0" layoutY="46.0"
prefHeight="45.0" prefWidth="116.0" />
<Label fx:id="outputLabel" layoutX="35.0" layoutY="92.0"
prefHeight="39.0" prefWidth="323.0" />
<Button fx:id="convertButton" layoutX="28.0" layoutY="140.0"
mnemonicParsing="false" onAction="#convertButtonListener" text="Convert
to miles" />
</children>
</AnchorPane>
KiloConverterController.java file
C:UsersChristopherDocumentsNetBeansProjectsJavaOPS_2019srcKilo
meterConverterController.java
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
public class KilometerConverterController
{
@FXML
private Button convertButton;
@FXML
private TextField kilometerTextField;
@FXML
private Label outputLabel;
@FXML
private Label promptLabel;
// This optional method is called when the FXML file is loaded.
public void initialize()
{
// Perform any necessary initialization here.
}
// Event listener for the convertButton
public void convertButtonListener()
{
final double CONVERSION_FACTOR = 0.6214;
// Get the kilometers from the TextField.
String str = kilometerTextField.getText();
// Convert kilometers to miles.
double miles = Double.parseDouble(str) * CONVERSION_FACTOR;
// Display the converted distance.
outputLabel.setText(str + " kilometers is " + miles + " miles.");
}
}
KiloConverter.java file
C:UsersChristopherDocumentsNetBeansProjectsJavaOPS_2019srcKilo
meterConverter.java
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
public class KilometerConverter extends Application
{
public void start(Stage stage) throws Exception
{
// Load the FXML file.
Parent parent =
FXMLLoader.load(getClass().getResource("KilometerConverter.fxml"));
// Build the scene graph.
Scene scene = new Scene(parent);
// Display our window, using the scene graph.
stage.setTitle("Kilometer Converter");
stage.setScene(scene);
stage.show();
}
public static void main(String[] args)
{
// Launch the application.
launch(args);
}
}
Ex1: Guesser Game. The use enters a number between 1 and 4. If the
guessed number is the same as the computer randomly generated
number between 1 and 4 the Guesser wins
package MyJavaLab;
import java.util.*;
public class Guesser
{
public static void main(String[]args)
{
Scanner input = new Scanner(System.in);
Random rand = new Random();
System.out.println("WELCOME TO THE GUESSING GAME");
System.out.println("PICK ANY NUMBER FROM 1 TO 4");
System.out.print("ENTER YOUR NUMBER >> ");
// this is where your number is inputed
int number = input.nextInt();
//this is where your computer inputs its value
//The random number generated with 4 as argument
//always fall between 0 and 3. So, 1 must be added
//because we don't want to enter 0, but 4 is a possible input.
int randnumb = 1 + rand.nextInt(4);
if (number == randnumb)
{
System.out.println("YOU WIN O !!! ");
}
else
{
System.out.println("TRY AGAIN ");
System.out.println("COMPUTER ENTERED " + randnumb);
}
}
}
EX2: This class ScoreGrader.java receives students scores and grade them
according to their classes as the application output.
package MyJavaLab;
import java.util.*;
public class ScoreGrader
{
public static void main(String[]args)
{
Scanner input = new Scanner(System.in);
System.out.println("Enter your Score ");
int score = input.nextInt();
if(score >= 70 && score <=100)
{
System.out.println("FIRST CLASS A++");
}
else if(score >= 60 && score <= 69)
{
System.out.println("SECOND CLASS B++");
}
else if(score >= 50 && score <= 59)
{
System.out.println("SECOND CLASS C");
}
else if(score >= 45 && score <= 49)
{
System.out.println("THIRD CLASS D");
}
else if(score >= 44 && score <= 36)
{
System.out.println("PASS E");
}
else if(score >= 0 && score <= 35)
{
System.out.println("FAIL F");
}
else
{
System.out.println("wrong Entry");
}
System.out.println("YOUR SCORE IS "+score);
}
}
EX3: This class, Randomizer.java generates a series of random numbers
(from 1 to 6) a hundred times, count the frequency for which each of the
numbers from 1 to 6 occurs and display the result of the frequency of
occurence by the particular number in the output.
package MyJavaLab;
import java.util.*;
public class Randomizer
{
public static void main(String []args)
{
int frqOne = 0;
int frqTwo = 0;
int frqThree = 0 ;
int frqFour = 0;
int frqFive = 0;
int frqSix = 0;
Random rand = new Random();
for (int i = 0; i <= 100; i++)
{
int number = 1+ rand.nextInt(6);
System.out.print(number + "");
switch (number)
{
case 1:
frqOne++;
break;
case 2:
frqTwo++;
break;
case 3:
frqThree++;
break;
case 4:
frqFour++;
break;
case 5:
frqFive++;
break;
case 6:
frqSix++;
break;
}
}
System.out.println("");
System.out.println("Number 1 was generated "+frqOne+" times");
System.out.println("Number 2 was generated "+frqTwo+" times");
System.out.println("Number 3 was generated "+frqThree+" times");
System.out.println("Number 4 was generated "+frqFour+" times");
System.out.println("Number 5 was generated "+frqFive+" times");
System.out.println("Number 6 was generated "+frqSix+" times");
}
}
EX4: Number Guess Game.
package gnumber;
import java.util.Random;
import java.util.Scanner;
public class GNumber
{
public static void main(String[] args)
{
int computerNumber;
int yourGuess;
Random myRandom = new Random();
Scanner myScanner = new Scanner(System.in);
//get the computer's number between 1 and 10
computerNumber = 1 + myRandom.nextInt(10);
System.out.println("I'm thinking of a number between 1 and 10 ");
//get your guess
System.out.print("What do you think it is? ");
yourGuess = myScanner.nextInt();
//analyze guess and get results
if(yourGuess == computerNumber) // you got it
{
System.out.println("You got it! That's my number!");
}
else if(yourGuess < computerNumber) //too low
{
System.out.println("You sre too low! My number was " +
computerNumber);
}
else //too high
{
System.out.println("You are too high! My number was " +
computerNumber);
}
}
}
Modified Number Guess Game
package newguess;
import java.util.Random;
import java.util.Scanner;
public class NewGuess
{
public static void main(String[] args)
{
int computerNumber;
int yourGuess;
Random myRandom = new Random();
Scanner myScanner = new Scanner(System.in);
//get the computer's number between 1 and 10
computerNumber = 1 + myRandom.nextInt(10);
System.out.println("I'm thinking of a number between 1 and 10");
do
{
//get your guess
System.out.print("What do you think it is? ");
yourGuess = myScanner.nextInt();
//analyze guess and get results
if(yourGuess == computerNumber) // you got it
{
System.out.println("You got it! That's my number! ");
}
else if(yourGuess < computerNumber) //too low
{
System.out.println("You sre too low! ");
}
else //too high
{
System.out.println("You are too high! " );
}
}
while(yourGuess != computerNumber);
}
}
Number Guess Game (Modified to count the number of guess before the
correct answer)
package newguess;
import java.util.Random;
import java.util.Scanner;
public class NewGuess
{
public static void main(String[] args)
{
int computerNumber;
int yourGuess;
int count = 0; // used to count the number of guesses made.
Random myRandom = new Random();
Scanner myScanner = new Scanner(System.in);
//get the computer's number between 1 and 10
computerNumber = 1 + myRandom.nextInt(10);
System.out.println("I'm thinking of a number between 1 and 10");
do
{
//get your guess
System.out.print("What do you think it is? ");
yourGuess = myScanner.nextInt();
//analyze guess and get results
if(yourGuess == computerNumber) // you got it
{
System.out.println("nYou got it! That's my number! ");
count = count + 1;
}
else if(yourGuess < computerNumber) //too low
{
System.out.println("nYou sre too low! ");
count = count + 1;
}
else //too high
{
System.out.println("nYou are too high! " );
count = count + 1;
}
System.out.println("nYou made " + count + " guesses ");
}
while(yourGuess!=computerNumber);
}
}
EX5: Code for generating a set of randomly generated numbers:
Note that this code is intwo parts – the second part being the method
that generates the random numbers
//First Part
package shuffle;
import java.util.Random;
public class Shuffle
{
public static void main(String[] args)
{
//declare needed array
int[] myIntegers = new int[10];
//shuffle integers from 0 to 9
myIntegers = nIntegers(10);
//print out results
for(int i = 0; i < 10; i++)
{
System.out.println("Value is " + myIntegers[i]);
}
}
//This code returns n randomly sorted integers
public static int[] nIntegers(int n)
{
/*
* Returns n randomly sorted integers 0 to n - 1
*/
int nArray[] = new int[n];
int temp, s;
Random myRandom = new Random();
// initialize array from 0 to n - 1
for (int i = 0; i < n; i++)
{
nArray[i] = i;
}
// perform one-card shuffle
// i is number of items remaining in list
// s is the random selection from that list
// we swap last item i – 1 with selection s
for (int i = n; i >= 1; i--)
{
s = myRandom.nextInt(i);
temp = nArray[s];
nArray[s] = nArray[i - 1];
nArray[i - 1] = temp;
}
return(nArray);
}
}
Java   small steps - 2019
EX 6: This code displays the elapsed time – Stopwatch counts in
milliseconds
package stopwatch;
import java.util.Scanner;
public class Stopwatch
{
public static void main(String[] args)
{
Scanner myScanner = new Scanner(System.in);
long startTime;
String stopIt = "";
while (!stopIt.equals("0"))
{
System.out.print("nPress <Enter> to start stopwatch. ");
myScanner.nextLine();
System.out.println("Stopwatch is running ...");
startTime = System.currentTimeMillis();
System.out.print("Press <Enter> to stop stopwatch (enter a 0 to stop the
program).");
stopIt = myScanner.nextLine();
System.out.println("Elapsed time is " + (System.currentTimeMillis() -
startTime) /
1000.0 + " seconds.");
}
}
}
EX7: Rolling Dice: This project draws 2 dicee and sums the numbers
displayed. The numbers displayed are showed on the die as graphics.
package dice;
import java.util.Scanner;
import java.util.Random;
public class Dice
{
public static void main(String[] args)
{
Scanner myScanner = new Scanner(System.in);
int die1;
int die2;
Random myRandom = new Random();
String stopIt = "";
do
{
System.out.println("nDice are rolling ...");
die1 = myRandom.nextInt(6) + 1;
drawDie(die1);
die2 = myRandom.nextInt(6) + 1;
drawDie(die2);
System.out.println("nTotal is: " + (die1 + die2));
System.out.print("Press <Enter> to roll again, enter a 0 to stop: ");
stopIt = myScanner.nextLine();
}
while (!stopIt.equals("0"));
}
public static void drawDie(int n)
{
// use character graphics to draw dice
System.out.println("n-----");
switch (n)
{
case 1:
// draw a die with one spot
System.out.println("| |");
System.out.println("| * |");
System.out.println("| |");
break;
case 2:
// draw a die with two spots
System.out.println("|* |");
System.out.println("| |");
System.out.println("| *|");
break;
case 3:
// draw a die with three spots
System.out.println("|* |");
System.out.println("| * |");
System.out.println("| *|");
break;
case 4:
// draw a die with four spots
System.out.println("|* *|");
System.out.println("| |");
System.out.println("|* *|");
break;
case 5:
// draw a die with five spots
System.out.println("|* *|");
System.out.println("| * |");
System.out.println("|* *|");
break;
case 6:
// draw a die with six spots
System.out.println("|* *|");
System.out.println("|* *|");
System.out.println("|* *|");
break;
}
System.out.println("-----");
}
}
EX8: This code display the states and their respective capital cities (US).
The states are randomly selected and 4 randomly selected capital cities
are displayed for the user to select the correct city.
package statecapitals;
import java.util.Scanner;
import java.util.Random;
public class StateCapitals
{
public static void main(String[] args)
{
Scanner myScanner = new Scanner(System.in);
Random myRandom = new Random();
int answer;
int capitalSelected = 0;
String[] state = new String[50];
String[] capital = new String[50];
int[] listedCapital = new int[4];
int[] capitalUsed = new int[50];
// initialize arrays
state[0] = "Alabama" ; capital[0] = "Montgomery";
state[1] = "Alaska" ; capital[1] = "Juneau";
state[2] = "Arizona" ; capital[2] = "Phoenix";
state[3] = "Arkansas" ; capital[3] = "Little Rock";
state[4] = "California" ; capital[4] = "Sacramento";
state[5] = "Colorado" ; capital[5] = "Denver";
state[6] = "Connecticut" ; capital[6] = "Hartford";
state[7] = "Delaware" ; capital[7] = "Dover";
state[8] = "Florida" ; capital[8] = "Tallahassee";
state[9] = "Georgia" ; capital[9] = "Atlanta";
state[10] = "Hawaii" ; capital[10] = "Honolulu";
state[11] = "Idaho" ; capital[11] = "Boise";
state[12] = "Illinois" ; capital[12] = "Springfield";
state[13] = "Indiana" ; capital[13] = "Indianapolis";
state[14] = "Iowa" ; capital[14] = "Des Moines";
state[15] = "Kansas" ; capital[15] = "Topeka";
state[16] = "Kentucky" ; capital[16] = "Frankfort";
state[17] = "Louisiana" ; capital[17] = "Baton Rouge";
state[18] = "Maine" ; capital[18] = "Augusta";
state[19] = "Maryland" ; capital[19] = "Annapolis";
state[20] = "Massachusetts" ; capital[20] = "Boston";
state[21] = "Michigan" ; capital[21] = "Lansing";
state[22] = "Minnesota" ; capital[22] = "Saint Paul";
state[23] = "Mississippi" ; capital[23] = "Jackson";
state[24] = "Missouri" ; capital[24] = "Jefferson City";
state[25] = "Montana" ; capital[25] = "Helena";
state[26] = "Nebraska" ; capital[26] = "Lincoln";
state[27] = "Nevada" ; capital[27] = "Carson City";
state[28] = "New Hampshire" ; capital[28] = "Concord";
state[29] = "New Jersey" ; capital[29] = "Trenton";
state[30] = "New Mexico" ; capital[30] = "Santa Fe";
state[31] = "New York" ; capital[31] = "Albany";
state[32] = "North Carolina" ; capital[32] = "Raleigh";
state[33] = "North Dakota" ; capital[33] = "Bismarck";
state[34] = "Ohio" ; capital[34] = "Columbus";
state[35] = "Oklahoma" ; capital[35] = "Oklahoma City";
state[36] = "Oregon" ; capital[36] = "Salem";
state[37] = "Pennsylvania" ; capital[37] = "Harrisburg";
state[38] = "Rhode Island" ; capital[38] = "Providence";
state[39] = "South Carolina" ; capital[39] = "Columbia";
state[40] = "South Dakota" ; capital[40] = "Pierre";
state[41] = "Tennessee" ; capital[41] = "Nashville";
state[42] = "Texas" ; capital[42] = "Austin";
state[43] = "Utah" ; capital[43] = "Salt Lake City";
state[44] = "Vermont" ; capital[44] = "Montpelier";
state[45] = "Virginia" ; capital[45] = "Richmond";
state[46] = "Washington" ; capital[46] = "Olympia";
state[47] = "West Virginia" ; capital[47] = "Charleston";
state[48] = "Wisconsin" ; capital[48] = "Madison";
state[49] = "Wyoming" ; capital[49] = "Cheyenne";
// begin questioning loop
do
{
// Generate the next question at random
answer = myRandom.nextInt(50);
// Display selected state
System.out.println("nState is: " + state[answer] + "n");
// capitalUsed array is used to see which state capitals have
//been selected as possible answers
for (int i = 0; i < 50; i++)
{
capitalUsed[i] = 0;
}
// Pick four different state indices (J) at random
// These are used to set up multiple choice answers
// Stored in the listedCapital array
for (int i = 0; i < 4; i++)
{
//Find value not used yet and not the answer
int j;
do
{
j = myRandom.nextInt(50);
}
while (capitalUsed[j] != 0 || j == answer);
capitalUsed[j] = 1;
listedCapital[i] = j;
}
// Now replace one item (at random) with correct answer
listedCapital[myRandom.nextInt(4)] = answer;
// Display multiple choice answers
for (int i = 0; i < 4; i++)
{
System.out.println((i + 1) + " - " + capital[listedCapital[i]]);
}
System.out.print("nWhat is the Capital? (Enter 0 to Stop) ");
capitalSelected = myScanner.nextInt();
// check answer
if (capitalSelected != 0)
{
if (listedCapital[capitalSelected - 1] == answer)
{
System.out.println("That's it ... good job!");
}
else
{
System.out.println("Sorry, the answer is " + capital[answer] +".");
}
}
}
while (capitalSelected != 0);
}
}
EX 9: This code calculate the total amount with weekly deposits and stated
annual interest rate.
NOTE: This worked examples also have severalexplanation. Read through the
comments to see the example of how to use the .nextLine() method if it is
preceeded by an int or Double variable;
package savings;
import java.util.Scanner;
public class Savings
{
public static void main(String[] args)
{
//declare and initialize variables;
String yourName;
double deposit = 0.0;
double rate =0.0; //annual interest rate expressed as double
int weeks = 0;
double total = 0.0;
double totalR = 0.0;
Scanner myScanner = new Scanner(System.in);
//ask for user name
System.out.println("Hello, what's your name? ");
yourName = myScanner.nextLine();
// get deposit amount
System.out.println("nHow much will you deposit each week? ");
deposit = myScanner.nextDouble();
//get number of weeks
System.out.println("For how many weeks? ");
weeks = myScanner.nextInt();
//what's the interest rate
System.out.println("Enter the interest rate ");
rate = myScanner.nextDouble();
//compute and display total
if(rate <= 0.0)
{
total = deposit * weeks;
System.out.print("n" + yourName + ", after " + weeks + " weeks, you will
have $"
+ total + ", in your savings.n");
}
else
{
total = (deposit * (Math.pow((1 + rate / 5200), weeks) - 1) / rate) * 5200;
System.out.print("n" + yourName + ", after " + weeks + " weeks, you will
have $"
+ total + ", in your savings.n");
}
}
}
With deposit = 10, weeks = 20, interest rate = 6.5.
With deposit = 10, weeks = 20, interest rate = 0.0;
EX10: Using Java to do a simulation program:
A very powerful use of computers is to do something called simulation.
Before building an actual airplane, companies “build” the plane on a computer
and simulate its performance. This is much cheaper and far safer than testing
actual airplanes. Engineers simulate how a building might react to an
earthquake to help them design better buildings. And, businesses use
computers to simulate how decisions could affect their profits. Based on
computer results, they decide how and where to invest their money. In this
project, we will build a small business simulation. We will simulate the
operation of the neighborhood kids’ backyard lemonade stand. Based on the
temperature, they set a selling price for their lemonade (the hotter it is, the
more they can charge). They will then be told how many cups were sold and
how much money was made. If the kids are too greedy, asking too much for
their product, they won’t sell as much. If they’re too nice, they won’t make as
much money. It’s a tough world out there! This project is saved as Lemonade.
Source: Beginning Java - Philip Conrod & Lou Tylee
©2015 Kidware Software LLC www.kidwaresoftware.com, page 130
Project Design
You’ll sell lemonade for five days (simulated days). On each day, you will be
told the temperature. Based on this temperature, you set a price for your
lemonade. You will be told how many cups of lemonade you sold and how
much
money you made. The steps to follow on each day:
1. Computer picks a random temperature.
2. You assign a price for each cup of lemonade.
3. Computer analyzes the information and computes number of cups sold.
4. Your sales are computed and displayed.
The first step is a straightforward use of the random number object. In the
second step, we will use the Scanner nextDouble method to get the price.
Step 3 is the difficult one – how does the computer determine cups sold? In
this project, we will give you the code to do this (code we made up) in the form
of a method you can use. This is something done all the time in programming
– borrowing and using someone else’s code. In this method, you provide
the temperature and the price (the arguments) and the method returns the
number of cups sold. Finally, the println method will be used to output the
results of each day’s sales.
Let me try to explain what I’m doing here. First, I assume there is a bestPrice
(most you can charge) for a cup of lemonade, based on the temperature (t).
You can charge more on hotter days. The equation used assumes this
bestPrice ranges from 20 cents at 60 degrees to a random value between 45
and 65 cents at 100 degrees. Similarly, there is a maximum number of cups
you can sell (maxSales) based on temperature. You can sell more on hotter
days.
The equation used assumes maxSales ranges from 20 cups at 60 degrees to
a random value between 150 and 250 at 100 degrees. Before returning a
number of cups, I compute an adjustment variable. This is used to adjust
your sales based on your input price. If you ask more than the bestPrice,
sales will suffer because people will think you are asking too much for your
product. Your sales will also suffer if you charge too little for lemonade! Why’s
that? Many
people think if something doesn’t cost enough, it may not be very good. You
just can’t win in the business world. So, adjustment is computed based on how
far your set price (p) is from the bestPrice. Once adjustment is found, it is
multiplied times the maxSales and returned to the calling program in this line
of code:
return((int) (adjustment * maxSales));
Notice you see something you have never seen before, the words int in
parentheses before the product. This is called a casting in Java and converts
the product (adjustment * maxSales), a double value, to the required int
return value for the number of cups sold. You can’t sell a fraction of a cup!
This brings up a good point. Many times, when using someone else’s Java
code, you may see things you don’t recognize. What do you do? The best
thing is to consult some Java reference (another Java programmer, a
textbook, the Java website) and do a little research and self-study. This helps
you learn more and helps you become a better Java programmer.
Notice if you play this program as a game, you wouldn’t know all the details
behind the rules (how cupSales are computed). You would learn these rules
as you play. That’s what happens in all computer games – the games have
rules and, after many plays, you learn what rules the programmers have
included. If you can’t follow all the math in the getSales method, that’s okay.
You don’t really need to – just trust that it does the job. Actually, Java
programmers use
methods all the time without an understanding of how they work (do you know
how Java finds the square root of a number?). In such cases, we rely on the
method writer to tell us what information is required (arguments) and what
information is computed (returned value) and trust that the method works.
That’s the beauty of methods – we get code without doing the work.
Below is the complete code:
package lemonade;
import java.util.Random;
import java.util.Scanner;
public class Lemonade
{
public static void main(String[] args)
{
// define variables
int dayNumber;
int temperature;
int cupPrice;
int cupsSold;
double daySales;
double totalSales;
Random myRandom = new Random();
Scanner myScanner = new Scanner(System.in);
// start loop of five days
dayNumber = 1;
totalSales = 0.0;
do
{
// pick a random temperature between 60 and 100
temperature = myRandom.nextInt(41) + 60;
System.out.println("nWelcome to Day " + dayNumber + ", the temperature is "
+ temperature + "
degrees.");
// get price
System.out.print("How many cents do you want to charge for a cup of
lemonade? ");
cupPrice = myScanner.nextInt();
// get cups sold, provide sales report
cupsSold = getSales(temperature, cupPrice);
daySales = cupsSold * cupPrice / 100.0;
totalSales = totalSales + daySales;
System.out.println("nYou sold " + cupsSold + " cups of lemonade, earning $"
+ daySales + ".");
if (dayNumber > 1)
{
System.out.println("Total sales after " + dayNumber + " days are $" +
totalSales + ".");
}
// go to next day
dayNumber = dayNumber + 1;
}
while (dayNumber < 6);
System.out.println("nThe lemonade stand is now closed.");
}
/ *
* getSales method
* input temperature t and price p
* output number of cups sold
* KIDware
*/
public static int getSales(int t, double p)
{
// t represents temperature
// p represents price
double bestPrice;
double maxSales;
double adjustment;
Random anotherRandom = new Random();
// find best price
bestPrice = (t - 60.0) * (45 - anotherRandom.nextInt(20)) / 40.0 + 20.0;
// find maximum sales
maxSales = (t - 60.0) * (230 -anotherRandom.nextInt(100)) / 40.0 + 20.0;
// find sales adjustment
adjustment = 1.0 - Math.abs((p - bestPrice) / bestPrice);
if (adjustment < 0.0)
{
adjustment = 0.0;
}
// return adjusted sales
return((int) (adjustment * maxSales));
}
}
Java   small steps - 2019
EX11. This method creates a “shuffled” array of 10 random numbers. Shuffling
routine using nIntegers() method
package shuffle;
import java.util.Random;
public class Shuffle
/*
This code creates an array of length 10. This array is then filled with the random integers 0 to
9 by calling the
nIntegers method. The results are printed using 10 calls to println in the for loop.
*/
{
public static void main(String[] args)
{
//declare needed array
int[] myIntegers = new int[10];
//shuffle integers from 0 to 9
myIntegers = nIntegers(10);
//print out results
for(int i = 0; i < 10; i++)
{
System.out.println("Value is " + myIntegers[i]);
}
}
/*
// Note: This is the nIntegers() method, it generates random integers from
0 to 9
*/
public static int[] nIntegers(int n)
{
/*
* Returns n randomly sorted integers 0 to n - 1
*/
int nArray[] = new int[n];
int temp, s;
Random myRandom = new Random();
// initialize array from 0 to n - 1
for (int i = 0; i < n; i++)
{
nArray[i] = i;
}
// perform one-card shuffle
// i is number of items remaining in list
// s is the random selection from that list
// we swap last item i – 1 with selection s
for (int i = n; i >= 1; i--)
{
s = myRandom.nextInt(i);
temp = nArray[s];
nArray[s] = nArray[i - 1];
nArray[i - 1] = temp;
}
return(nArray);}}
Java   small steps - 2019
EX12: Card Wars
In this project, we create a simplified version of the kid’s card game - War. You
play against the computer. You each get half a deck of cards (26 cards). Each
player turns over one card at a time. The one with the higher card wins the
other player’s card. The one with the most cards at the end wins.
We can use our shuffle routine to shuffle the deck of cards (compute 52
random integers from 0 to 51). Describing the handed-out cards requires
converting the integer card value to an actual card in the deck (value and suit).
We will create a Java method to do this. Comparing the cards is relatively
easy (we’ll add the capability to our card display method), as is updating and
displaying the scores (we will use our old friend, the println method). No input
is ever needed from the user (besides pressing a key on the keyboard to see
the cards) – he/she merely watches the results go by.
Project Development
Before building the project, let’s do a little “up front” work. In the Project
Design, we see a need for a method that,
given a card number (0 to 51), (1) determines and displays which card (suit,
value) in a deck it represents, and (2)
determines its corresponding numerical value to allow comparisons. We will
create this method now.
Displaying a card consists of answering two questions: what is the card suit
and what is the card value? The four suits are hearts, diamonds, clubs, and
spades. The thirteen card values, from lowest to highest, are: Two, Three,
Four, Five, Six, Seven, Eight, Nine, Ten, Jack, Queen, King, Ace. We’ve seen
in our shuffle routine that a card number will range from 0 to 51. How do we
translate that card number to a card suit and value? (Notice the distinction
between card number and card value - card number ranges from 0 to 51,
card value can only range from Two to Ace.) We need to develop some type of
translation rule. This is done all the time in Java. If the number you compute
with or work with does not directly translate to information you need, you need
to make up rules to do the translation. For example, the numbers 1 to 12 are
used to represent the months of the year. But, these numbers tell us nothing
about the names of the month. We need a rule to translate each number to a
month name.
We know we need 13 of each card suit. Hence, an easy rule to decide suit is:
cards numbered 0 - 12 are hearts, cards numbered 13 - 25 are diamonds,
cards numbered 26 - 38 are clubs, and cards numbered 39 - 51 are spades.
For card values, lower numbers should represent lower cards. A rule that does
this for each number in each card suit is:
As examples, notice card 22 is a Jack of Diamonds. Card 30 is a Six of Clubs.
We now have the ability to describe a card. How do we compare them?
Card comparisons must be based on a numerical value, not displayed card
value -it’s difficult to check if King is
greater than Seven, though it can be done. So, one last rule is needed to
relate card value to numerical value. It’s a
simple one - start with a Two having a numerical value of 0 (lowest) and go up,
with an Ace having a numerical value of 12 (highest). This makes numerical
card comparisons easy. Notice hearts card numbers already go from 0 to 12. If
we subtract 13 from diamonds numbers, 26 from clubs numbers, and 39 from
spades numbers, each of those card numbers will also range from 0 to 12.
This gives a common basis for comparing cards. This all may seem
complicated, but look at the Java code and you’ll see it really isn’t.
The Java method (cardDisplay) that takes the card number (n) as an input
and returns its numeric value (0 to 12)
to allow comparisons. The method also prints a string description (value and
suit) of the corresponding card, using the above table for translation.
public static int cardDisplay(int n)
{
// given card number n (0 - 51), prints description
// and returns numeric value
String suit;
String[] value = new String[13];
value[0] = "Two";
value[1] = "Three";
value[2] = "Four";
value[3] = "Five";
value[4] = "Six";
value[5] = "Seven";
value[6] = "Eight";
value[7] = "Nine";
value[8] = "Ten";
value[9] = "Jack";
value[10] = "Queen";
value[11] = "King";
value[12] = "Ace";
// determine your card's suit, adjust numeric value n
if (n >= 0 && n <= 12)
{
suit = "Hearts";
}
else if (n >= 13 && n <= 25)
{
suit = "Diamonds";
n = n - 13;
}
else if (n >= 26 && n <= 38)
{
suit = "Clubs";
n = n - 26;
}
else
{
suit = "Spades";
n = n - 39;
}
// print description
System.out.println(value[n] + " of " + suit);
// return numeric value
return(n);
}
You should be able to see how this works. With this method built, we can use
it to create the complete Card Wars
project.
The following are the complete codes for the CardWars project:
/*The Game Concept is as follows:
1. Shuffle a deck of cards.
2. Computer gives itself a card and player a card.
3. Computer compares cards, the player with the higher card wins both cards.
4. Scores are computed and displayed.
5. Process continues until all cards have been dealt from the deck.
*/
package cardwars;
import java.util.Random;
import java.util.Scanner;
public class CardWars
{
public static void main(String[] args)
{
// declare needed variables in main method
int cardIndex = 0;
int computerScore = 0;
int yourScore = 0;
int computerCard;
int yourCard;
int[] myCards = new int[52];
Scanner myScanner = new Scanner(System.in);
// shuffle the cards
myCards = nIntegers(52);
// do loop starting the game
do
{
// display computer card, then your card. This code picks and displays the
cards
System.out.print("My card: ");
computerCard = cardDisplay(myCards[cardIndex]);
System.out.print("Your card: ");
yourCard = cardDisplay(myCards[cardIndex + 1]);
// see who won (or if there is a tie) and compute the scores
if (yourCard > computerCard)
{
System.out.println("You win!");
yourScore = yourScore + 2;
}
else if (computerCard > yourCard)
{
System.out.println("I win!");
computerScore = computerScore + 2;
}
else
{
System.out.println("It's a tie.");
yourScore = yourScore + 1;
computerScore = computerScore + 1;
}
//Next we print the results:
System.out.println("My Score: " + computerScore);
System.out.println("Your Score: " + yourScore);
cardIndex = cardIndex + 2;
System.out.print("There are " + (52 - cardIndex) + " cards remaining. ");
System.out.println("Press any key.");
myScanner.nextLine();
}
while ((52 - cardIndex) > 0);
System.out.println("Game over.");
}
//Card Display: This is the method that display a randomly selected card
public static int cardDisplay(int n)
{
// given card number n (0 - 51), prints description and returns numeric value
String suit;
String[] value = new String[13];
value[0] = "Two";
value[1] = "Three";
value[2] = "Four";
value[3] = "Five";
value[4] = "Six";
value[5] = "Seven";
value[6] = "Eight";
value[7] = "Nine";
value[8] = "Ten";
value[9] = "Jack";
value[10] = "Queen";
value[11] = "King";
value[12] = "Ace";
// determine your card's suit, adjust numeric value n
if (n >= 0 && n <= 12)
{
suit = "Hearts";
}
else if (n >= 13 && n <= 25)
{
suit = "Diamonds";
n = n - 13;
}
else if (n >= 26 && n <= 38)
{
suit = "Clubs";
n = n - 26;
}
else
{
suit = "Spades";
n = n - 39;
}
// print description
System.out.println(value[n] + " of " + suit);
// return numeric value
return(n);
}
// This is the Shuffle Method. It returns n randomly sorted integers from 0
to n - 1
public static int[] nIntegers(int n)
{
// Returns n randomly sorted integers from 0 to n - 1
int nArray[] = new int[n];
int temp, s;
Random myRandom = new Random();
// initialize array from 0 to n - 1
for (int i = 0; i < n; i++)
{
nArray[i] = i;
}
// perform one-card shuffle
// i is number of items remaining in list
// s is the random selection from that list
// we swap last item i - 1 with selection s
for (int i = n; i >= 1; i--)
{
s = myRandom.nextInt(i);
temp = nArray[s];
nArray[s] = nArray[i - 1];
nArray[i - 1] = temp;
}
return(nArray);
}
}
Java   small steps - 2019
EX13: Units Converter class: - This class converts length from one unit of
measure (inch, foot, yard, mile, centimeter, meter, kilometer) to another. The
idea of the program is simple. Type a value and choose its units. Display that
value converted to several other units. Note how the conversion factors are
stored in a two-dimensional array (table).
package converter;
import java.util.Scanner;
public class Converter
{
public static void main(String[] args)
{
//Declare Variables
Scanner myScanner = new Scanner(System.in);
String[] units = new String[7];
double[][] conversions = new double[7][7];
double fromValue;
int fromUnits;
/*
Establish conversion factors - stored in a 2 - dimensional array
or table = the first number is the table row, the second number
is the table column.
*/
conversions[0][0] = 1.0; //inches to inches
conversions[0][1] = 1.0/12.0; //inches to feet
conversions[0][2] = 1.0/36.0; //inches to yard
conversions[0][3] = (1.0/12)/5280.0; //inches to mile
conversions[0][4] = 2.54; // inches to cm
conversions[0][5] = 2.54/100; //inches to km
conversions[0][6] = 2.54/100000; //inches to km
for (int i = 0; i<7; i++)
{
conversions[1][i] = 12.0 * conversions[0][i];
conversions[2][i] = 36.0 * conversions[0][i];
conversions[3][i] = 5280.0 *(12.0 * conversions[0][i]);
conversions[4][i] = conversions[0][i] / 2.54;
conversions[5][i] = 100.0 * conversions[0][i] / 2.54;
conversions[6][i] = 100000.0 * (conversions[0][i] /2.54);
}
//initialize variables
units[0] = "inches (in)";
units[1] = "feet (ft) ";
units[2] = "yards (yd) ";
units[3] = "miles (mi)";
units[4] = "centimeters (cm)";
units[0] = "metres (m)";
units[0] = "kilometers (km)";
//trick Java into continuing loop
while(1 != 2)
{
System.out.print("nEnter a value to convert (Enter 0 to stop): ");
fromValue = myScanner.nextDouble();
if (fromValue == 0)
{
break;
}
for (int i = 0; i < 7; i++)
{
System.out.println(i + 1 + " - " + units[i]);
}
do
{
System.out.println("What unit is the value in? ");
fromUnits = myScanner.nextInt();
}
while (fromUnits < 1 || fromUnits > 7);
// arrays are zero-based, so subtract 1
fromUnits = fromUnits -1;
// Do unit conversion
System.out.println("n" + fromValue + " " + units[fromUnits] + " is:n");
for (int i = 0; i < 7; i++)
{
System.out.println(fromValue * conversions[fromUnits][i] + " " + units[i]);
}
}
}
}
Java   small steps - 2019
EX14: Multiplication Table: This program generates 2 random numbers from 1
to 12 and ask you to find the product. Giving the answer for wrong responses
and calculating the percentage of correct answers at the end.
package timestables;
import java.util.Random;
import java.util.Scanner;
public class TimesTables
{
public static void main(String[] args)
{
Scanner myScanner = new Scanner(System.in);
//Variables declaraton
int number1, number2;
int product;
int yourAnswer;
int numProb;
int numRight;
Random myRandom = new Random();
numProb = 0;
numRight = 0;
//display the problem
for(int i = 1; i < 13; i++)
{
numProb = numProb + 1;
//Generate Random numbers for factors
number1 = myRandom.nextInt(13);
number2 = myRandom.nextInt(13);
// find product
product = number1 * number2;
System.out.println("nProblem " + numProb + " : ");
System.out.print("What is " + number1 + " X " + number2 + " = ") ;
yourAnswer = myScanner.nextInt();
//Check answer and update score
if(yourAnswer == product)
{
numRight = numRight + 1;
System.out.println("That's correct!");
}
else
{
System.out.println("Answer is " + product);
}
System.out.println("Score: " + 100.0*numRight/numProb + "%");
}
}
}
EX15 Loan Repayment Calculator: Given a loan amount, annual interest rate
and the number of months for repayment.
package loan;
import java.util.Scanner;
public class Loan
{
public static void main(String[] args)
{
//this next line just ricks Java to keep the loop going
while (1 != 2)
{
Scanner myScanner = new Scanner(System.in);
//declare variables
double loan;
double interest;
int months;
double payment;
double multiplier;
//input values
System.out.println("Enter loan amount (Enter 0 to stop): ");
loan = myScanner.nextDouble();
System.out.println("Enter yearly interest rate: ");
interest = myScanner.nextDouble();
System.out.println("Enter number of months to pay back the loan; ");
months = myScanner.nextInt();
//compute interest multiplier
multiplier = Math.pow((1 + interest/1200), months);
//compute payment
payment = loan * interest * multiplier / (1200 * (multiplier - 1));
System.out.println("Your monthly payment in $" + payment + "n");
}
}
}
EX16: Portfolio Value
/*
* In this project, we will build a tool that lets you determine the current value
* of your stock holdings. You store when you bought a particular stock, how
* many shares you bought and how much you paid. Then, whenever you
want,
* you enter current values to determine your gain (or possible losses).
*
* In this program, you need to store information about your stocks (date
purchased,
* purchase price and shares owned) in arrays. When the program runs, you
select
* a stock. Then, you type in the current price and you will be shown the
current
* value and yearly return for that stock. Notice how we limit the choice of stock
* number and how all the dates are formatted and used.
*/
package portfolio;
import java.util.Date;
import java.text.DateFormat;
import java.util.Scanner;
public class Portfolio
{
public static void main(String[] args)
{
Scanner myScanner = new Scanner(System.in);
// declare variables
int numberStocks;
int currentStock;
double currentPrice;
double currentValue;
double currentReturn;
String[] stockDate = new String[25];
String[] stockName = new String[25];
double[] stockPrice= new double[25];
int[] stockShares = new int[25];
Date today = new Date();
Date display = new Date();
// Set Stock Information
numberStocks = 5;
stockDate[0] = "5/1/00" ; stockName[0] = "Accellup";
stockPrice[0] = 30 ; stockShares[0] = 200;
stockDate[1] = "2/1/99" ; stockName[1] = "Guaranty";
stockPrice[1] = 10 ; stockShares[1] = 100;
stockDate[2] = "3/1/99" ; stockName[2] = "Diamond Bank";
stockPrice[2] = 20 ; stockShares[2] = 300;
stockDate[3] = "4/1/99" ; stockName[3] = "Dangote Flour";
stockPrice[3] = 15 ; stockShares[3] = 200;
stockDate[4] = "4/10/02" ; stockName[4] = "Halliburton";
stockPrice[4] = 40 ; stockShares[4] = 400;
System.out.println("nToday is: " +
DateFormat.getDateInstance(DateFormat.FULL).format(today));
// trick Java into repeating loop
while (1 != 2)
{
System.out.println("nYour Stocks:");
for (int i = 0; i < numberStocks; i++)
{
System.out.println(i + 1 + " - " + stockName[i]);
}
do
{
System.out.print("nPick a stock (Or Enter 0 to STOP) ");
currentStock = myScanner.nextInt();
}
while (currentStock < 0 || currentStock > numberStocks);
if (currentStock == 0)
{
break;
}
currentStock = currentStock - 1;
System.out.println("nStock: " + stockName[currentStock]);
// convert string date to Date class for display
try
{
display =
DateFormat.getDateInstance(DateFormat.SHORT).parse(stockDate[currentSt
ock]);
}
catch(java.text.ParseException e)
{
System.out.println("Error parsing date" + e);
}
System.out.println("Date Purchased: " +
DateFormat.getDateInstance(DateFormat.FULL).format(display));
System.out.println("Purchase Price: $" + stockPrice[currentStock]);
System.out.println("Shares Held: " + stockShares[currentStock]);
System.out.println("Initial Value: $" + stockPrice[currentStock] *
stockShares[currentStock]);
System.out.print("What is current selling price? ");
currentPrice = myScanner.nextDouble();
// compute todays value and percent return
currentValue = currentPrice * stockShares[currentStock];
System.out.println("Current Value: $" + currentPrice *
stockShares[currentStock]);
// Daily increase
long diffDays = (today.getTime() - display.getTime()) / (24 * 60 * 60 *
1000);
currentReturn = (currentValue / (stockPrice[currentStock] *
stockShares[currentStock]) - 1) /
diffDays;
// Yearly return
currentReturn = 100 * (365 * currentReturn);
System.out.println("Yearly return: " + currentReturn + "%");
}
}
}
Java   small steps - 2019
EX17: Demonstrating typical steps for creating a GUI app
1. The JStopwatch application
2. The GridBag layout for setting control positions
3. The steps taken:
 Declare and create the control (class level scope):
ControlType controlName = new ControlType();
 Position the control:
gridConstraints.gridx = desiredColumn;
gridConstraints.gridy = desiredRow;
getContentPane().add(controlName, gridConstraints);
(assumes a gridConstraints object has been created).
 Add the control listener:
controlName.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
controlNameActionPerformed(e);
}
});
 Write the control event method:
private void controlNameActionPerformed(ActionEvent e)
{
[Java code to execute]
}
4. JStopwatch.java class
package jstopwatch;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class JStopwatch extends JFrame
{
// declare controls used
JButton startButton = new JButton();
JButton stopButton = new JButton();
JButton exitButton = new JButton();
JLabel startLabel = new JLabel();
JLabel stopLabel = new JLabel();
JLabel elapsedLabel = new JLabel();;
JTextField startTextField = new JTextField();
JTextField stopTextField = new JTextField();
JTextField elapsedTextField = new JTextField();
// declare class level variables
long startTime;
long stopTime;
double elapsedTime;
//next is the main method
public static void main(String args[])
{
new JStopwatch().show();
}
// frame constructor. This constructor is used for creating
the //JStopwatch frame
public JStopwatch()
{
setTitle("Stopwatch Application");
//code for exiting the form (class)
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
exitForm(e);
}
});
//declares the type of form layout used – GridBag in this
case
getContentPane().setLayout(new GridBagLayout());
// Add controls, each in their respective grid x, y
//coordinates
GridBagConstraints gridConstraints = new
GridBagConstraints();
startButton.setText("Start Timing"); //start timing button
gridConstraints.gridx = 0;
gridConstraints.gridy = 0;
getContentPane().add(startButton, gridConstraints);
//adds action listener for Start Timing event
startButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
startButtonActionPerformed(e);
}
});
//Stop button added into grid position
stopButton.setText("Stop Timing"); gridConstraints.gridx
= 0;
gridConstraints.gridy = 1;
getContentPane().add(stopButton, gridConstraints);
//adds ActionListener for Stop timing event
stopButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
stopButtonActionPerformed(e);
}
});
//adds Exit button added into grid position
exitButton.setText("Exit");
gridConstraints.gridx = 0;
gridConstraints.gridy = 2;
getContentPane().add(exitButton, gridConstraints);
//adds action listener for Exit button – closing the
application
exitButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
exitButtonActionPerformed(e);
}
});
startLabel.setText("Start Time"); //label
gridConstraints.gridx = 1;
gridConstraints.gridy = 0;
getContentPane().add(startLabel, new
GridBagConstraints());
stopLabel.setText("Stop Time"); //label
gridConstraints.gridx = 1;
gridConstraints.gridy = 1;
getContentPane().add(stopLabel, gridConstraints);
elapsedLabel.setText("Elapsed Time (sec)"); //label
gridConstraints.gridx = 1;
gridConstraints.gridy = 2;
getContentPane().add(elapsedLabel, gridConstraints);
startTextField.setText("");
startTextField.setColumns(15); //text field for Start time
gridConstraints.gridx = 2;
gridConstraints.gridy = 0;
getContentPane().add(startTextField, new
GridBagConstraints());
stopTextField.setText(""); //text field for Stop time
stopTextField.setColumns(15);
gridConstraints.gridx = 2;
gridConstraints.gridy = 1;
getContentPane().add(stopTextField, gridConstraints);
elapsedTextField.setText(""); //text field for Elapsed
time
elapsedTextField.setColumns(15);
gridConstraints.gridx = 2;
gridConstraints.gridy = 2;
getContentPane().add(elapsedTextField, gridConstraints);
pack();
}
//the following event method is performed with click of
Start button
private void startButtonActionPerformed(ActionEvent e)
{
// click of start timing button
startTime = System.currentTimeMillis();
startTextField.setText(String.valueOf(startTime));
stopTextField.setText("");
elapsedTextField.setText("");
}
//the following event method is performed with click of
Stop button
private void stopButtonActionPerformed(ActionEvent e)
{
// click of stop timing button
stopTime = System.currentTimeMillis();
stopTextField.setText(String.valueOf(stopTime));
elapsedTime = (stopTime - startTime) / 1000.0;
elapsedTextField.setText(String.valueOf(elapsedTime));
}
//the method for closing and exiting the frame
private void exitButtonActionPerformed(ActionEvent e)
{
System.exit(0);
}
private void exitForm(WindowEvent e)
{
System.exit(0);
} }
EX18. Savings Account
This project determines how much you save by making monthly deposits into a savings
account. The mathematical formula used is:
F = D[(1 + I)M
– 1)] / I
where
F - Final amount
D - Monthly deposit amount
I - Monthly interest rate
M - Number of months
Savings Account GUI class
1. For this class, first start with the basic GUI template
package savings.account;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class SavingsAccount extends JFrame
{
public static void main(String[] args)
{ //Construct the frame (by calling the SavingsAccount() constructor)
new SavingsAccount().show();
}
public SavingsAccount() //constructor
{
//code to build the form and add all its elements
setTitle("Savings Account");
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
exitForm(e);
}
});
getContentPane().setLayout(new GridBagLayout());
}
private void exitForm(WindowEvent e)
{
System.exit(0); } }
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~`
2. The layout used GridBagLayout form takes this shape
X = 0 X = 1
Y=
0
deposit Label depositTextField
Y=
1
yearly Interest Label interestTextField
Y
=
2
number OfMonths
Label
monthsTextField
Y
=
3
finalBalance Label finalTextField
Y
=
4
calculateButton Exit Button
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~`
3. And this is the final product
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~`
NEXT YOU WRITE THE CODES AS FOLLOWS
package savings.account;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.text.*;
public class SavingsAccount extends JFrame
{
//add the needed controls for the class
JLabel depositLabel = new JLabel();
JLabel interestLabel = new JLabel();
JLabel monthsLabel = new JLabel();
JLabel finalLabel = new JLabel();
JTextField depositTextField = new JTextField();
JTextField interestTextField = new JTextField();
JTextField monthsTextField = new JTextField();
JTextField finalTextField = new JTextField();
JButton calculateButton = new JButton();
JButton exitButton = new JButton();
//next comes the main class that houses the constructor
public static void main(String args[])
{
//construct frame - the main calls the SavingsAccount() constructor below
new SavingsAccount().show();
}
public SavingsAccount() //this is the SavingsAccount() constructor
{
// code to build the form and add all its elements are placed here
setTitle("Savings Account");
addWindowListener(new WindowAdapter() //this code for Exit of the
{ //form with click of X button
public void windowClosing(WindowEvent e)
{
exitForm(e);
}
});
// position controls on the form (& establish event methods)
getContentPane().setLayout(new GridBagLayout());
GridBagConstraints gridConstraints = new GridBagConstraints();
depositLabel.setText("Monthly Deposit");
gridConstraints.gridx = 0;
gridConstraints.gridy = 0;
getContentPane().add(depositLabel, gridConstraints);
interestLabel.setText("Yearly Interest");
gridConstraints.gridx = 0;
gridConstraints.gridy = 1;
getContentPane().add(interestLabel, gridConstraints);
monthsLabel.setText("Number of Months");
gridConstraints.gridx = 0;
gridConstraints.gridy = 2;
getContentPane().add(monthsLabel, gridConstraints);
finalLabel.setText("Final Balance");
gridConstraints.gridx = 0;
gridConstraints.gridy = 3;
getContentPane().add(finalLabel, gridConstraints);
depositTextField.setText("");
depositTextField.setColumns(10);
gridConstraints.gridx = 1;
gridConstraints.gridy = 0;
getContentPane().add(depositTextField, gridConstraints);
interestTextField.setText("");
interestTextField.setColumns(10);
gridConstraints.gridx = 1;
gridConstraints.gridy = 1;
getContentPane().add(interestTextField, gridConstraints);
monthsTextField.setText("");
monthsTextField.setColumns(10);
gridConstraints.gridx = 1;
gridConstraints.gridy = 2;
getContentPane().add(monthsTextField, gridConstraints);
finalTextField.setText("");
finalTextField.setFocusable(false);
finalTextField.setColumns(10);
gridConstraints.gridx = 1;
gridConstraints.gridy = 3;
getContentPane().add(finalTextField, gridConstraints);
calculateButton.setText("Calculate"); //this button has the
gridConstraints.gridx = 0; //ActionListener placed after its placement
gridConstraints.gridy = 5;
getContentPane().add(calculateButton, gridConstraints);
calculateButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e) //actionPerformed with
{ //the click of Calculate button
calculateButtonActionPerformed(e);
}
});
exitButton.setText("Exit"); //Closes the SavingsAccount form
exitButton.setFocusable(false);
gridConstraints.gridx = 1;
gridConstraints.gridy = 5;
getContentPane().add(exitButton, gridConstraints);
exitButton.addActionListener(new ActionListener() //ActionListener for Exit
button
{
public void actionPerformed(ActionEvent e) //actionPerformed on click of Exit
button
{
exitButtonActionPerformed(e);
}
});
pack(); } //marking the end of the GridBagLout and its contents
//ActionPerformed events along with the variables and the methods that run to do the
calculations
// go here. The codes for the two //events are placed immediately following the
constructor
private void calculateButtonActionPerformed(ActionEvent e)
{
double deposit;
double interest;
double months;
double finalBalance;
double monthlyInterest;
// read values from text fields
deposit = Double.valueOf(depositTextField.getText()).doubleValue();
interest = Double.valueOf(interestTextField.getText()).doubleValue();
monthlyInterest = interest / 1200;
months = Double.valueOf(monthsTextField.getText()).doubleValue();
// compute final value and put the value in the text field;
finalBalance = deposit * (Math.pow((1 + monthlyInterest), months) - 1) /
monthlyInterest;
finalTextField.setText(new DecimalFormat("0.00").format(finalBalance));
}
//actionPerformed on click of Exit button
private void exitButtonActionPerformed(ActionEvent e) {
System.exit(0);
}
private void exitForm(WindowEvent e) //the Exit Window method
{
System.exit(0);
}
}
EX19: Password Validation Example
package password;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Password extends JFrame
{
JLabel passwordLabel = new JLabel();
JPasswordField inputPasswordField = new JPasswordField();
JButton validButton = new JButton();
JButton exitButton = new JButton();
public static void main(String args[])
{
//construct frame
new Password().show();
}
public Password()
{
// code to build the form
setTitle("Password Validation");
setResizable(false);
getContentPane().setBackground(Color.yellow);
//this code is window closing ActionListener
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
exitForm(e);
}
});
// position controls
getContentPane().setLayout(new GridBagLayout());
GridBagConstraints gridConstraints;
passwordLabel.setText("Please Enter Your Password:");
passwordLabel.setOpaque(true);
passwordLabel.setBackground(Color.white);
passwordLabel.setFont(new Font("Arial", Font.BOLD, 14));
passwordLabel.setBorder(BorderFactory.createLoweredBevelBorder());
passwordLabel.setHorizontalAlignment(SwingConstants.CENTER);
gridConstraints = new GridBagConstraints();
gridConstraints.ipadx = 30;
gridConstraints.ipady = 20;
gridConstraints.gridx = 0;
gridConstraints.gridy = 0;
gridConstraints.insets = new Insets(5, 20, 5, 20);
getContentPane().add(passwordLabel, gridConstraints);
inputPasswordField.setText("");
inputPasswordField.setFont(new Font("Arial", Font.PLAIN, 14));
inputPasswordField.setColumns(15);
gridConstraints = new GridBagConstraints();
gridConstraints.gridx = 0;
gridConstraints.gridy = 1;
getContentPane().add(inputPasswordField, gridConstraints);
inputPasswordField.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
inputPasswordFieldActionPerformed(e);
}
});
validButton.setText("Validate");
gridConstraints = new GridBagConstraints();
gridConstraints.gridx = 0;
gridConstraints.gridy = 2;
getContentPane().add(validButton, gridConstraints);
validButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
validButtonActionPerformed(e);
}
});
exitButton.setText("Exit");
gridConstraints = new GridBagConstraints();
gridConstraints.gridx = 0;
gridConstraints.gridy = 3;
getContentPane().add(exitButton, gridConstraints);
exitButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
exitButtonActionPerformed(e);
}
});
pack();
//This code set the password screen at the centre of the monitor
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
setBounds((int) (0.5 * (screenSize.width - getWidth())), (int) (0.5 *
(screenSize.height - getHeight())),
getWidth(), getHeight());
}
private void inputPasswordFieldActionPerformed(ActionEvent e)
{
validButton.doClick();
}
private void validButtonActionPerformed(ActionEvent e)
{
final String THEPASSWORD = "LetMeIn";
//This procedure checks the input password
int response;
if (inputPasswordField.getText().equals(THEPASSWORD))
{
// If correct, display message box
JOptionPane.showConfirmDialog(null, "You've passed security!", "Access
Granted",
JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE);
}
else
{
// If incorrect, give option to try again
response = JOptionPane.showConfirmDialog(null, "Incorrect password -
Try Again?",
"AccessDenied", JOptionPane.YES_NO_OPTION,
JOptionPane.ERROR_MESSAGE);
if (response == JOptionPane.YES_OPTION)
{
inputPasswordField.setText("");
inputPasswordField.requestFocus();
}
else
{
exitButton.doClick();
}
}
}
private void exitButtonActionPerformed(ActionEvent e)
{
System.exit(0);
}
private void exitForm(WindowEvent e)
{
System.exit(0);
}
}
EX 20. Pizza Order Form
package pizza;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Pizza extends javax.swing.JFrame
{
JPanel sizePanel = new JPanel(); //these are class level declarations
ButtonGroup sizeButtonGroup = new ButtonGroup();
JRadioButton smallRadioButton = new JRadioButton();
JRadioButton mediumRadioButton = new JRadioButton();
JRadioButton largeRadioButton = new JRadioButton();
JPanel crustPanel = new JPanel();
ButtonGroup crustButtonGroup = new ButtonGroup();
JRadioButton thinRadioButton = new JRadioButton();
JRadioButton thickRadioButton = new JRadioButton();
JPanel toppingsPanel = new JPanel();
JCheckBox cheeseCheckBox = new JCheckBox();
JCheckBox mushroomsCheckBox = new JCheckBox();
JCheckBox olivesCheckBox = new JCheckBox();
JCheckBox onionsCheckBox = new JCheckBox();
JCheckBox peppersCheckBox = new JCheckBox();
JCheckBox tomatoesCheckBox = new JCheckBox();
ButtonGroup whereButtonGroup = new ButtonGroup();
JRadioButton eatInRadioButton = new JRadioButton();
JRadioButton takeOutRadioButton = new JRadioButton();
JButton buildButton = new JButton();
JButton exitButton = new JButton();
String pizzaSize;
String pizzaCrust;
String pizzaWhere;
JCheckBox[] topping = new JCheckBox[6];
public static void main(String args[])
{
// construct frame
new Pizza().show();
}
public Pizza()
{
setTitle("Pizza Order");
setResizable(true);
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
exitForm(e);
} });
getContentPane().setLayout(new GridBagLayout()); //ContentPane hold all the
controls
GridBagConstraints gridConstraints; //position controls
sizePanel.setLayout(new GridBagLayout());
sizePanel.setBorder(BorderFactory.createTitledBorder("Size")) ;
smallRadioButton.setText("Small");
smallRadioButton.setSelected(true);
sizeButtonGroup.add(smallRadioButton); //you add smallRadioButton to
sizeButtonGroup
gridConstraints = new GridBagConstraints();
gridConstraints.gridx = 0;
gridConstraints.gridy = 0;
gridConstraints.anchor = GridBagConstraints.WEST;
sizePanel.add(smallRadioButton, gridConstraints); //you also add button to
panel
smallRadioButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
sizeRadioButtonActionPerformed(e);
}
});
mediumRadioButton.setText("Medium");
sizeButtonGroup.add(mediumRadioButton);
gridConstraints = new GridBagConstraints();
gridConstraints.gridx = 0;
gridConstraints.gridy = 1;
gridConstraints.anchor = GridBagConstraints.WEST;
sizePanel.add(mediumRadioButton, gridConstraints);
mediumRadioButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
sizeRadioButtonActionPerformed(e);
}
});
largeRadioButton.setText("Large");
largeRadioButton.setSelected(true);
sizeButtonGroup.add(largeRadioButton);
gridConstraints = new GridBagConstraints();
gridConstraints.gridx = 0;
gridConstraints.gridy = 2;
gridConstraints.anchor = GridBagConstraints.WEST;
sizePanel.add(largeRadioButton, gridConstraints);
largeRadioButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
sizeRadioButtonActionPerformed(e);
}
});
gridConstraints = new GridBagConstraints();
gridConstraints.gridx = 0;
gridConstraints.gridy = 0;
getContentPane().add(sizePanel, gridConstraints);
crustPanel.setLayout(new GridBagLayout());
crustPanel.setBorder(BorderFactory.createTitledBorder("Crust"));
thinRadioButton.setText("Thin Crust");
thinRadioButton.setSelected(true);
crustButtonGroup.add(thinRadioButton);
gridConstraints = new GridBagConstraints();
gridConstraints.gridx = 0;
gridConstraints.gridy = 0;
gridConstraints.anchor = GridBagConstraints.WEST;
crustPanel.add(thinRadioButton, gridConstraints);
thinRadioButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
crustRadioButtonActionPerformed(e);
}
});
thickRadioButton.setText("Thick Crust");
crustButtonGroup.add(thickRadioButton);
gridConstraints = new GridBagConstraints();
gridConstraints.gridx = 0;
gridConstraints.gridy = 1;
gridConstraints.anchor = GridBagConstraints.WEST;
crustPanel.add(thickRadioButton, gridConstraints);
thickRadioButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
crustRadioButtonActionPerformed(e);
}
});
gridConstraints = new GridBagConstraints();
gridConstraints.gridx = 0;
gridConstraints.gridy = 1;
getContentPane().add(crustPanel, gridConstraints); //you add the crustPanel to
ContentPane
toppingsPanel.setLayout(new GridBagLayout());
toppingsPanel.setBorder(BorderFactory.createTitledBorder("Toppings"))
;
cheeseCheckBox.setText("Extra Cheese");
gridConstraints = new GridBagConstraints();
gridConstraints.gridx = 0;
gridConstraints.gridy = 0;
gridConstraints.anchor = GridBagConstraints.WEST;
toppingsPanel.add(cheeseCheckBox, gridConstraints);
mushroomsCheckBox.setText("Mushrooms");
gridConstraints = new GridBagConstraints();
gridConstraints.gridx = 0;
gridConstraints.gridy = 1;
gridConstraints.anchor = GridBagConstraints.WEST;
toppingsPanel.add(mushroomsCheckBox, gridConstraints);
olivesCheckBox.setText("Olives");
gridConstraints = new GridBagConstraints();
gridConstraints.gridx = 0;
gridConstraints.gridy = 2;
gridConstraints.anchor = GridBagConstraints.WEST;
toppingsPanel.add(olivesCheckBox, gridConstraints);
onionsCheckBox.setText("Onions");
gridConstraints = new GridBagConstraints();
gridConstraints.gridx = 1;
gridConstraints.gridy = 0;
gridConstraints.anchor = GridBagConstraints.WEST;
toppingsPanel.add(onionsCheckBox, gridConstraints);
peppersCheckBox.setText("Green Peppers");
gridConstraints = new GridBagConstraints();
gridConstraints.gridx = 1;
gridConstraints.gridy = 1;
gridConstraints.anchor = GridBagConstraints.WEST;
toppingsPanel.add(peppersCheckBox, gridConstraints);
tomatoesCheckBox.setText("Tomatoes");
gridConstraints = new GridBagConstraints();
gridConstraints.gridx = 1;
gridConstraints.gridy = 2;
gridConstraints.anchor = GridBagConstraints.WEST;
toppingsPanel.add(tomatoesCheckBox, gridConstraints);
gridConstraints = new GridBagConstraints();
gridConstraints.gridx = 1;
gridConstraints.gridy = 0;
gridConstraints.gridwidth = 2;
getContentPane().add(toppingsPanel, gridConstraints); //adds the
toppingsPanel
//to the Content
Pane
eatInRadioButton.setText("Eat In");
eatInRadioButton.setSelected(true);
whereButtonGroup.add(eatInRadioButton);
gridConstraints = new GridBagConstraints();
gridConstraints.gridx = 1;
gridConstraints.gridy = 1;
gridConstraints.anchor = GridBagConstraints.WEST;
getContentPane().add(eatInRadioButton, gridConstraints);
eatInRadioButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
whereRadioButtonActionPerformed(e);
}
});
takeOutRadioButton.setText("Take Out");
whereButtonGroup.add(takeOutRadioButton);
gridConstraints = new GridBagConstraints();
gridConstraints.gridx = 2;
gridConstraints.gridy = 1;
gridConstraints.anchor = GridBagConstraints.WEST;
getContentPane().add(takeOutRadioButton, gridConstraints);
takeOutRadioButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
whereRadioButtonActionPerformed(e);
}
});
buildButton.setText("Build Pizza");
gridConstraints = new GridBagConstraints();
gridConstraints.gridx = 1;
gridConstraints.gridy = 2;
getContentPane().add(buildButton, gridConstraints);
buildButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
buildButtonActionPerformed(e);
}
});
exitButton.setText("Exit");
gridConstraints = new GridBagConstraints();
gridConstraints.gridx = 2;
gridConstraints.gridy = 2;
getContentPane().add(exitButton, gridConstraints);
exitButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
exitButtonActionPerformed(e);
}
});
pack();
//the following lines of code centralize the Pizza order form
Dimension screenSize =
Toolkit.getDefaultToolkit().getScreenSize(); setBounds((int) (0.5 *
(screenSize.width - getWidth())), (int)
(0.5 * (screenSize.height - getHeight())), getWidth(), getHeight());
// Initialize parameters
pizzaSize = smallRadioButton.getText();
pizzaCrust = thinRadioButton.getText();
pizzaWhere = eatInRadioButton.getText();
// Define an array of topping check boxes
topping[0] = cheeseCheckBox;
topping[1] = mushroomsCheckBox;
topping[2] = olivesCheckBox;
topping[3] = onionsCheckBox;
topping[4] = peppersCheckBox;
topping[5] = tomatoesCheckBox;
}
private void sizeRadioButtonActionPerformed(ActionEvent e)
{
pizzaSize = e.getActionCommand();
}
private void crustRadioButtonActionPerformed(ActionEvent e)
{
pizzaCrust = e.getActionCommand();
}
private void whereRadioButtonActionPerformed(ActionEvent e)
{
pizzaWhere = e.getActionCommand();
}
private void buildButtonActionPerformed(ActionEvent e)
{
// This procedure builds a confirm dialog box that displays your pizza
type
String message;
message = pizzaWhere + "n";
message += pizzaSize + " Pizza" + "n";
message += pizzaCrust + "n";
// Check each topping using the array we set up
for (int i = 0; i < 6; i++)
{
if (topping[i].isSelected())
{
message += topping[i].getText() + "n";
}
}
JOptionPane.showConfirmDialog(null, message, "Your Pizza",
JOptionPane.DEFAULT_OPTION,
JOptionPane.INFORMATION_MESSAGE);
}
private void exitButtonActionPerformed(ActionEvent e)
{
System.exit(0);
}
private void exitForm(WindowEvent e)
{
System.exit(0);
}
}
EX 21: Flight Planner
On running the application and clicking assign, we have;
package flight;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Flight extends JFrame
{ //class wide labels added below as needed
JLabel citiesLabel = new JLabel();
JList citiesList = new JList();
JScrollPane citiesScrollPane = new JScrollPane();
JLabel seatLabel = new JLabel();
JComboBox seatComboBox = new JComboBox();
JLabel mealLabel = new JLabel();
JComboBox mealComboBox = new JComboBox();
JButton assignButton = new JButton();
JButton exitButton = new JButton();
public static void main(String[] args)
{
// Construct frame
new Flight().show();
}
public Flight()
{
//Create frame
setTitle("Flight Planner");
setResizable(false);
addWindowListener(new WindowAdapter() //for exiting on clicking X
on the form
{
public void windowClosing(WindowEvent e)
{
exitForm(e);
}
});
getContentPane().setLayout(new GridBagLayout()); //type of layout for
the ContentPane
GridBagConstraints gridConstraints; //creating layout type which
is GridBag
citiesLabel.setText("Destination City"); // add citiesLabel to GridBag
gridConstraints = new GridBagConstraints();
gridConstraints.gridx = 0;
gridConstraints.gridy = 0;
gridConstraints.insets = new Insets(10, 0, 0, 0);
getContentPane().add(citiesLabel, gridConstraints); //adds citiesLabel to
ContentPane
citiesScrollPane.setPreferredSize(new Dimension(150, 100)); //position
ScrollPane in GridBag
citiesScrollPane.setViewportView(citiesList);
gridConstraints = new GridBagConstraints();
gridConstraints.gridx = 0;
gridConstraints.gridy = 1;
gridConstraints.insets = new Insets(10, 10, 10, 10);
getContentPane().add(citiesScrollPane, gridConstraints); //adds
ScrollPane to ContentPane
DefaultListModel citiesListModel = new DefaultListModel(); // list of
cities
citiesListModel.addElement("San Diego");
citiesListModel.addElement("Los Angeles");
citiesListModel.addElement("Orange County");
citiesListModel.addElement("Ontario");
citiesListModel.addElement("Bakersfield");
citiesListModel.addElement("Oakland");
citiesListModel.addElement("Sacramento");
citiesListModel.addElement("San Jose");
citiesListModel.addElement("San Francisco");
citiesListModel.addElement("Eureka");
citiesListModel.addElement("Eugene");
citiesListModel.addElement("Portland");
citiesListModel.addElement("Spokane");
citiesListModel.addElement("Seattle");
citiesList.setModel(citiesListModel);
citiesList.setSelectedIndex(0);
seatLabel.setText("Seat Location"); // seatLabel positioned in GridBag
gridConstraints = new GridBagConstraints();
gridConstraints.gridx = 1;
gridConstraints.gridy = 0;
gridConstraints.insets = new Insets(10, 0, 0, 0);
getContentPane().add(seatLabel, gridConstraints); // seatLabel added to
ContentPane
seatComboBox.setBackground(Color.YELLOW); // position ComboBox
in the GridBag
seatComboBox.setPreferredSize(new Dimension(100, 25));
gridConstraints = new GridBagConstraints();
gridConstraints.gridx = 1;
gridConstraints.gridy = 1;
gridConstraints.insets = new Insets(10, 0, 0, 0);
gridConstraints.anchor = GridBagConstraints.NORTH;
getContentPane().add(seatComboBox, gridConstraints); // adding the
seatComboBox to ContentPane
seatComboBox.addItem("Aisle"); // seatComboBox items
seatComboBox.addItem("Middle");
seatComboBox.addItem("Window");
seatComboBox.setSelectedIndex(0);
mealLabel.setText("Meal Preference"); // mealLabel positioned in
GridBag
gridConstraints = new GridBagConstraints();
gridConstraints.gridx = 2;
gridConstraints.gridy = 0;
gridConstraints.insets = new Insets(10, 0, 0, 0);
getContentPane().add(mealLabel, gridConstraints); // add mealLabel to
ContentPane
mealComboBox.setEditable(true); // mealComboBox added to the
GridBag
gridConstraints = new GridBagConstraints();
gridConstraints.gridx = 2;
gridConstraints.gridy = 1;
gridConstraints.insets = new Insets(10, 10, 0, 10);
gridConstraints.anchor = GridBagConstraints.NORTH;
getContentPane().add(mealComboBox, gridConstraints); // add
mealBoxCombo to ContentPane
mealComboBox.setSelectedItem("No Preference"); // mealComboBox
items
mealComboBox.addItem("Chicken");
mealComboBox.addItem("Mystery Meat");
mealComboBox.addItem("Kosher");
mealComboBox.addItem("Vegetarian");
mealComboBox.addItem("Fruit Plate");
assignButton.setText("Assign"); // add assignButton to the GridBag
gridConstraints = new GridBagConstraints();
gridConstraints.gridx = 1;
gridConstraints.gridy = 2;
gridConstraints.insets = new Insets(0, 0, 10, 0);
getContentPane().add(assignButton, gridConstraints); // add assignButton to
ContentPane
assignButton.addActionListener(new ActionListener() // assignButton
ActionListener
{
public void actionPerformed(ActionEvent e)
{
assignButtonActionPerformed(e);
}
});
exitButton.setText("Exit"); // adds exitButton to the GridBag layout
gridConstraints = new GridBagConstraints();
gridConstraints.gridx = 2;
gridConstraints.gridy = 2;
gridConstraints.insets = new Insets(0,0,10, 0);
getContentPane().add(exitButton, gridConstraints); // adds exitButton
to ContentPane
exitButton.addActionListener(new ActionListener() // ActionListener
for exitButton
{
public void actionPerformed(ActionEvent e)
{
exitButtonActionPerformed(e);
}
});
pack(); // this line ends the GridBagLayout setting
// The next lines of code centers the form in the middle of the computer
screen
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
setBounds((int) (0.5*(screenSize.width = getWidth())),
(int) (0.5*(screenSize.height - getHeight())), getWidth(), getHeight());
}
private void exitForm(WindowEvent e) // method for exitForm on click of
exitButton
{
System.exit(0);
}
// the method below performs what happens on click of assignButton
private void assignButtonActionPerformed(ActionEvent e)
{
// Build message box that gives your assignment
String message;
message = "Destination: " +
citiesList.getSelectedValue() + "n";
message += "Seat Location: " +
seatComboBox.getSelectedItem() + "n";
message += "Meal: " + mealComboBox.getSelectedItem() + "n";
JOptionPane.showConfirmDialog(null, message, "Your Assignment",
JOptionPane.DEFAULT_OPTION,
JOptionPane.INFORMATION_MESSAGE);
}
//the method below exits the application on click of exitButton
private void exitButtonActionPerformed(ActionEvent e)
{
System.exit(0);
}
}
Next CHALLENGE
Question 2 - Page 115
In the “Game Zone” section in Chapter 1, you learned how to obtain a random
number. For example, the following statement generates a random number
between the constants MIN and MAX inclusive and assigns it to a variable
named random: random = 1 + (int)(Math.random() * MAX);
Write a program that selects a random number between 1 and 5 and asks the
user to guess the number. Display a message that indicates the difference
between the random number and the user’s guess. Display another message
that displays the random number and the Boolean value true or false
depending on whether the user’s guess equals the random number. Save the
file as RandomGuessMatch.java.
Page 116 = Case Problems
Case Problems
1. Carly’s Catering provides meals for parties and special events. Write a
program that prompts the user for the number of guests attending an event
and then computes the total price, which is $35 per person. Display the
company motto with the border that you created in the CarlysMotto2 class in
Chapter 1, and then display the number of guests, price per guest, and total
price. Also display a message that indicates true or false epending on whether
the job is classified as a large event—an event with 50 or more guests. Save
the file as CarlysEventPrice.java.
2. Sammy’s Seashore Supplies rents beach equipment such as kayaks,
canoes, beach chairs, and umbrellas to tourists. Write a program that prompts
the user for the number of minutes he rented a piece of sports equipment.
Compute the rental cost as $40 per hour plus $1 per additional minute. (You
might have surmised
already that this rate has a logical flaw, but for now, calculate rates as
described here. You can fix the problem after you read the chapter on decision
making.) Display Sammy’s motto with the border that you created in the
SammysMotto2 class in Chapter 1. Then display the hours, minutes, and total
price. Save the
file as SammysRentalPrice.java.
Page 237 – Gregorian Calendar
8. Write an application that uses methods in the GregorianCalendar class to
calculate how many days are left until the first day of next month. Save the file
as NextMonth.java.
9. Write an application that uses methods in the GregorianCalendar class to
calculate the number of days from today until the end of the current year. Save
the file as YearEnd.java.

More Related Content

PPTX
Software estimation techniques
PPTX
Program development life cycle
PDF
COCOMO Model By Dr. B. J. Mohite
PPTX
Expense_Tracker.pptx
PDF
Spm ap-network model-
PDF
MATERIAL.pdf
PPTX
Learn software development
PDF
Spm project planning
Software estimation techniques
Program development life cycle
COCOMO Model By Dr. B. J. Mohite
Expense_Tracker.pptx
Spm ap-network model-
MATERIAL.pdf
Learn software development
Spm project planning

What's hot (20)

PPSX
Exception Handling
PPTX
C++ decision making
PPTX
AWT Packages , Containers and Components
PPTX
Polymorphism in java
DOCX
Autoboxing and unboxing
PPTX
Java exception handling
PPTX
Decision Making and Looping
PDF
Operators in PHP
PPTX
Storage classes in c++
PPTX
Event Handling in java
PPTX
Java Data Types
PPTX
Polymorphism
PPT
Switch statements in Java
PPTX
Formatted Console I/O Operations in C++
PPT
Polymorphism in c++ ppt (Powerpoint) | Polymorphism in c++ with example ppt |...
PPT
Input and output in C++
PPSX
Java &amp; advanced java
PPTX
Type casting in c programming
Exception Handling
C++ decision making
AWT Packages , Containers and Components
Polymorphism in java
Autoboxing and unboxing
Java exception handling
Decision Making and Looping
Operators in PHP
Storage classes in c++
Event Handling in java
Java Data Types
Polymorphism
Switch statements in Java
Formatted Console I/O Operations in C++
Polymorphism in c++ ppt (Powerpoint) | Polymorphism in c++ with example ppt |...
Input and output in C++
Java &amp; advanced java
Type casting in c programming
Ad

Similar to Java small steps - 2019 (20)

DOCX
PROGRAMMING QUESTIONS.docx
PPTX
Java Foundations: Data Types and Type Conversion
DOCX
Cmis 212 module 2 assignment
DOCX
Cmis 212 module 2 assignment
DOCX
Cmis 212 module 2 assignment
PPTX
02. Data Types and variables
PDF
Java practical N Scheme Diploma in Computer Engineering
PDF
Microsoft word java
PDF
Java Question-Bank-Class-8.pdf
PDF
Sam wd programs
PPTX
Icom4015 lecture3-f17
PPT
Chapter 4 Powerpoint
PPTX
Core java
PDF
Lab exam question_paper
DOC
Practical java
DOC
Java final lab
PDF
Assignment 6 as a reference public class ArrExample pr.pdf
DOCX
Project 2Project 2.pdfIntroduction to Programming EECS 1.docx
PROGRAMMING QUESTIONS.docx
Java Foundations: Data Types and Type Conversion
Cmis 212 module 2 assignment
Cmis 212 module 2 assignment
Cmis 212 module 2 assignment
02. Data Types and variables
Java practical N Scheme Diploma in Computer Engineering
Microsoft word java
Java Question-Bank-Class-8.pdf
Sam wd programs
Icom4015 lecture3-f17
Chapter 4 Powerpoint
Core java
Lab exam question_paper
Practical java
Java final lab
Assignment 6 as a reference public class ArrExample pr.pdf
Project 2Project 2.pdfIntroduction to Programming EECS 1.docx
Ad

More from Christopher Akinlade (7)

PDF
Calculating Meter Factor for HT-400 Pumps.pdf
PDF
Pragmatic Approaches to Project Costs Estimation
PDF
Java q ref 2018
PDF
Basic photography workshop
PPTX
Now, That You're the PM What Comes Next?
PDF
Java quick reference v2
PDF
Calculating Meter Factor for HT-400 Pumps.pdf
Pragmatic Approaches to Project Costs Estimation
Java q ref 2018
Basic photography workshop
Now, That You're the PM What Comes Next?
Java quick reference v2

Recently uploaded (20)

PPTX
CHAPTER 12 - CYBER SECURITY AND FUTURE SKILLS (1) (1).pptx
PDF
Nekopoi APK 2025 free lastest update
PPTX
Agentic AI : A Practical Guide. Undersating, Implementing and Scaling Autono...
PDF
Audit Checklist Design Aligning with ISO, IATF, and Industry Standards — Omne...
PPTX
Odoo POS Development Services by CandidRoot Solutions
PPTX
ISO 45001 Occupational Health and Safety Management System
PPTX
ai tools demonstartion for schools and inter college
PDF
Which alternative to Crystal Reports is best for small or large businesses.pdf
PDF
System and Network Administration Chapter 2
PPTX
Lecture 3: Operating Systems Introduction to Computer Hardware Systems
PDF
Odoo Companies in India – Driving Business Transformation.pdf
PDF
Flood Susceptibility Mapping Using Image-Based 2D-CNN Deep Learnin. Overview ...
PDF
Addressing The Cult of Project Management Tools-Why Disconnected Work is Hold...
PPTX
Introduction to Artificial Intelligence
PDF
Claude Code: Everyone is a 10x Developer - A Comprehensive AI-Powered CLI Tool
PDF
Internet Downloader Manager (IDM) Crack 6.42 Build 41
PDF
Navsoft: AI-Powered Business Solutions & Custom Software Development
PDF
SAP S4 Hana Brochure 3 (PTS SYSTEMS AND SOLUTIONS)
PDF
Why TechBuilder is the Future of Pickup and Delivery App Development (1).pdf
PDF
Digital Strategies for Manufacturing Companies
CHAPTER 12 - CYBER SECURITY AND FUTURE SKILLS (1) (1).pptx
Nekopoi APK 2025 free lastest update
Agentic AI : A Practical Guide. Undersating, Implementing and Scaling Autono...
Audit Checklist Design Aligning with ISO, IATF, and Industry Standards — Omne...
Odoo POS Development Services by CandidRoot Solutions
ISO 45001 Occupational Health and Safety Management System
ai tools demonstartion for schools and inter college
Which alternative to Crystal Reports is best for small or large businesses.pdf
System and Network Administration Chapter 2
Lecture 3: Operating Systems Introduction to Computer Hardware Systems
Odoo Companies in India – Driving Business Transformation.pdf
Flood Susceptibility Mapping Using Image-Based 2D-CNN Deep Learnin. Overview ...
Addressing The Cult of Project Management Tools-Why Disconnected Work is Hold...
Introduction to Artificial Intelligence
Claude Code: Everyone is a 10x Developer - A Comprehensive AI-Powered CLI Tool
Internet Downloader Manager (IDM) Crack 6.42 Build 41
Navsoft: AI-Powered Business Solutions & Custom Software Development
SAP S4 Hana Brochure 3 (PTS SYSTEMS AND SOLUTIONS)
Why TechBuilder is the Future of Pickup and Delivery App Development (1).pdf
Digital Strategies for Manufacturing Companies

Java small steps - 2019

  • 2. JAVA CODING EXERCISES Practise ANSWERS to Exercise Questions Java Programming 7th Edition by Joyce Farrell Chapter 2: Chapter 3: 3, 4, 6, 7, 8, 9, 10, 11, 12, C1, 13, 14, Chapter 4: EX1, EX2, 1, 2, 3, 4, 6, 5, 7 Chapter 5: 1, 2, 3, 4, 5, 6, 7, 8, 9 Chapter 6: EXL1, EXL2, 3, 1, 2, 5, 6, 4, 9, 10 Chapter 7: EXL1, EXL2, EX3, EX4 Chapter 8: 1, Chapter 9: EX1, EX2, EX3, EX4, EX5 Chapter 12: EX1, EX2, EX3, EX4, EX5 Chapter 14: EX1, Chapter 16: EX1, Others: EX1, EX2, EX3, EX4, EX5, EX6, EX7, EX8, EX9, EX10, EX11, EX12 , EX13, EX14, EX15. EX16, EX17, EX18, EX19, EX20, EX21 Additional Examples from: Java for Kids – NetBeans8 Programming Tutorial 8th Edition – ©Philip Conrod & Lou Tylee. ©2015 Kidware Software LLC; www.kidwaresoftware.com Source: Beginning Java - Philip Conrod & Lou Tylee ©2015 Kidware Software LLC; www.kidwaresoftware.com (NOTE: All these practice files must be in the same folder or package because some classes are dependent on others.)
  • 3. QUESTION Write a Java class that declares a named constant that holds the number of feet in a mile: 5,280. Also declare a variable to represent the distance in miles between your house and your uncle’s house. Assign an appropriate value to the variable— for example, 8.5. Compute and display the distance to your uncle’s house in both miles and feet. Display explanatory text with the values—for example, The distance to my uncle's house is 8.5 miles or 44880.0 feet. Save the class as MilesToFeet.java. public class MilesToFeet { public static void main(String[] args) { double distanceInMiles = 8.5; final float MILES_TO_FEET = 5280; double distanceInFeet = distanceInMiles * MILES_TO_FEET; //float distanceInMiles = 8.5; // distanceInFeet = float (MILE_TO_FEET * distanceInMiles); System.out.println("Distance in Miles " + distanceInMiles); System.out.println("Distance in feet " + distanceInFeet); } } Miles to Feet Interactive Convert the MilesToFeet class to an interactive application. Instead of assigning a value to the distance, accept the value from the user as input. Save the revised class as MilesToFeetInteractive.java. import javax.swing.JOptionPane; public class MilesToFeetInteractive { public static void main(String[] args) { String milesString; //declare milesString as String variable double distanceInFeet; //declare distanceInFeet as a double variable final float MILES_TO_FEET = 5280; //declare MILES_TO_FLEET (comversion factor)as a float varaible with a constant value of 5280 //the next line of code displays a dialog box for inputing the distance in miles milesString = JOptionPane.showInputDialog(null, "Distance in Miles ", "Enter distance in miles", JOptionPane.INFORMATION_MESSAGE); //the next line is the code for doing the conversion distanceInFeet = Double.parseDouble(milesString) * MILES_TO_FEET; //the next line of code displays an information box with the answer! JOptionPane.showMessageDialog(null, "Distance in feet is " + distanceInFeet); }}
  • 4. 5a Write a Java class that declares a named constant that represents next year’s anticipated 10 percent increase in sales for each division of a company. (You can represent 10 percent as 0.10.) Also declare variables to represent this year’s sales total in dollars for the North and South divisions. Assign appropriate values to the variables—for example, 4000 and 5500. Compute and display, with explanatory text, next year public class ProjectedSales { public static void main(String[] args) { final double PERCENT_INCREASE = 0.10; //10% annual increase declared as a fixed double CONSTANT int divNorth, divSouth; //This year's sales declared as integers divNorth = 4000; //Value of this year's sales for division North divSouth = 5500; //Value of this year's sales for South division double projectedDivNorth, projectedDivSouth; //projected sales for next year declared as double variables projectedDivNorth = (1 + PERCENT_INCREASE) * divNorth; //CALCULATING NEXT YEAR PROJECTED SALES FOR NORTH DIVISION projectedDivSouth = (1 + PERCENT_INCREASE) * divSouth; //CALCULATING NEXT YEAR PROJECTED SALES FOR SOUTH DIVISION System.out.println("Projected next year sales for North division " + projectedDivNorth); System.out.println("Projected next year sales for South division " + projectedDivSouth); } }
  • 5. 5b. Convert the ProjectedSales class to an interactive application. Instead of assigning values to the North and South current year sales variables, accept them from the user as input. Save the revised class as ProjectedSalesInteractive.java. import javax.swing.JOptionPane; //import javax swing JOption method public class ProjectedSalesInteractive { //the name of the application is ProjectedSalesIncrease public static void main(String[] args) { //the start of the main program final double PERCENT_INCREASE = 0.10; //10% projected increase declared as a constant variable = 0.10 String percentIncrease; //the percentage increase declared as aString double projectedDivNorth, projectedDivSouth; //next year projected sales declared as a double variable //the code below opens a dialog box where we can enter the value for this year's North division sales as a String variable percentIncrease = JOptionPane.showInputDialog(null, "This years sales for North division in $ is ", "North Division ", JOptionPane.INFORMATION_MESSAGE); //the codes below executes and display the value of projected next year sales for South division as a double projectedDivNorth = Double.parseDouble(percentIncrease) * (1 + PERCENT_INCREASE); JOptionPane.showMessageDialog(null, "Projected North division sales for next year is " + projectedDivNorth); percentIncrease = JOptionPane.showInputDialog(null, "This years sales for South division in $ is ", "South Division ", JOptionPane.INFORMATION_MESSAGE); //the codes below executes and display the value of projected next year sales for South division as a double projectedDivSouth = Double.parseDouble(percentIncrease) * (1+ PERCENT_INCREASE); JOptionPane.showMessageDialog(null, "Projected South division sales is " + projectedDivSouth); } }
  • 6. 6. a. Write a class that declares a variable named inches that holds a length in inches, and assign a value. Display the value in feet and inches; for example, 86 inches becomes 7 feet and 2 inches. Be sure to use a named constant where appropriate. Save the class as InchesToFeet.java. public class InchesToFeet { public static void main(String[] args) { //inches to feet (12 inches equals 1 foot) //declare integer variable INCHES_TO_FEET with constant value final int INCHES_TO_FEET_FACTOR = 12; // declare lengthInInches as integer with an initial value of 81 feet int lengthInInches = 72; //declare lengthInInches, LengthInFeetPart, lengthInInchesPart as integers //lengthInFeetPart is the whole part of the division representing # of feet //lengthInInchesPart is the remainder after the division is made - using the % operator int lengthInFeetPart, lengthInInchesPart; //integer division of feet by 12 to give feet (feet/12) lengthInFeetPart = lengthInInches / (INCHES_TO_FEET_FACTOR); //mod, that is % division to give the inchees part lengthInInchesPart = lengthInInches % INCHES_TO_FEET_FACTOR; //print the whole feet part of the conversion System.out.print(lengthInFeetPart + " feet "); //print the inches part of the conversion by the side of the feet part on the same line. System.out.print(lengthInInchesPart + " inches "); } }
  • 7. 6b. Write an interactive version of the InchesToFeet class that accepts the inches value from a user. Save the class as inchesToFeetInteractive.java. import javax.swing.JOptionPane; public class InchesToFeetInteractive { //Converting from Inchees to Feet public static void main(String[] args) { //the main program starts here //12 inches = 1 foot, this is a CONSTANT integer declaration final int INCHES_TO_FEET_FACTOR = 12; //the length to be entered into the dialog box declared as a string value String inches; //all measured length are declared as integers int lengthInInches, lengthInInchesPart, lengthInFeetPart; //the measured length in inches is entered into the dialog box inches = JOptionPane.showInputDialog(null, "Length in inches", "Enter length in inches", JOptionPane.INFORMATION_MESSAGE); //the length entered into the dialog box as string is parsed into an integer lengthInInches = Integer.parseInt(inches); //inches is converted into feet - this is the whole part of the division lengthInFeetPart = lengthInInches / (INCHES_TO_FEET_FACTOR); //the mod that is % division of the measured length = the inches part lengthInInchesPart = lengthInInches % INCHES_TO_FEET_FACTOR; //Message box displays the measured length in feet and inches JOptionPane.showMessageDialog(null, "Length is " + lengthInFeetPart + " feet " + lengthInInchesPart + " inches"); //NOTE THAT THIS WILL NOT WORK FOR FLOAT OR DECIMAL NUMBERS } }
  • 8. 11. Write a program that accepts a temperature in Fahrenheit from a user and converts it to Celsius by subtracting 32 from the Fahrenheit value and multiplying the result by 5/9. Display both values. Save the class as FahrenheitToCelsius.java. public class FahrenheitToCelsius { public static void main(String[] args) { float temperatureInFahrenheit = 900; float temperatureInCelsius = 5 * (temperatureInFahrenheit - 32)/9; System.out.println(temperatureInFahrenheit + "F is equal to " + temperatureInCelsius + "C"); } } INTERACTIVE VERSION import javax.swing.JOptionPane; public class FahrenheitToCelsiusInteractive { public static void main(String[] args) { float temperatureInFahrenheit; String fahrenheitString; fahrenheitString = JOptionPane.showInputDialog(null, "Temperature in Fahrenheit ", "Enter temperature in Fahrenheit", JOptionPane.INFORMATION_MESSAGE); temperatureInFahrenheit = Float.parseFloat(fahrenheitString); float temperatureInCelsius = 5 * (temperatureInFahrenheit - 32)/9; JOptionPane.showMessageDialog(null, temperatureInFahrenheit + " F" + " is equal to " + temperatureInCelsius + " C"); } }
  • 9. 8a. Meadowdale Dairy Farm sells organic brown eggs to local customers. They charge $3.25 for a dozen eggs, or 45 cents for individual eggs that are not part of a dozen. Write a class that prompts a user for the number of eggs in the order and then display the amount owed with a full explanation. For example, typical output might be, “You ordered 27 eggs. That’s 2 dozen at $3.25 per dozen and 3 loose eggs at 45.0 cents each for a total of $7.85.” Save the class as Eggs.java. public class Eggs { public static void main(String[] arguments) { //price per dozen eggs = $3.25 final double PRICE_PER_DOZEN = 3.25; //price per single unit egg = 45cents ($0.45) final double PRICE_PER_UNIT_EGGS = 0.45; // a dozen = 12 final int ONE_DOZEN = 12; //all the variables above are declared as constants. //Per dozen price, per unit price, total amount paid //declared as double variables double costForDozens, costForUnits, totalAmount; //#of eggs purchased, #of dozens, # of single units //declared as integers int numberOfEggsPurchased = 27; int numberOfDozens, numberOfUnitEggs; //how many dozens are in the quantity purchased? numberOfDozens = numberOfEggsPurchased / 12; //how many single units are left after getting the 3 of dozens in the purchase? numberOfUnitEggs = numberOfEggsPurchased % 12; //amount paid for the # of dozens portion.
  • 10. costForDozens = numberOfDozens * PRICE_PER_DOZEN; //amount paid for the single eggss portion costForUnits = numberOfUnitEggs * PRICE_PER_UNIT_EGGS; //below is the total amount paid in $ totalAmount = costForDozens + costForUnits; //message displayed at the end of the calculation System.out.print(" You ordered 27 eggs. That is "); System.out.print(numberOfDozens +" dozens "); System.out.print(" at $3.25 per dozen and "); //System.out.print(" You ordered 27 eggs. That is " + numberOfDozens " at $3,25 per dozen "); System.out.print(numberOfUnitEggs + " eggs at 45.0 cents each for a total of $" + totalAmount + (" ")); } }
  • 11. 8b. INTERACTIVE VERSION OF 8a import javax.swing.JOptionPane; public class EggsInteractive { public static void main(String[] args) { //price per dozen eggs = $3.25 final double PRICE_PER_DOZEN = 3.25; //price per single unit egg = 45cents ($0.45) final double PRICE_PER_UNIT_EGGS = 0.45; // a dozen = 12 final int ONE_DOZEN = 12; //all the variables above are declared as constants. //Per dozen price, per unit price, total amount paid //declared as double variables double costForDozens, costForUnits, totalAmount; String howManyEggs; //the number of eggs ordered declared as a string int numberOfEggsPurchased; // number of eggs ordered as an integer //the number of eggs entered into the dialog box as a string howManyEggs = JOptionPane.showInputDialog(null, "Number of eggs ordered ", "Enter the number of eggs you want to buy.", JOptionPane.INFORMATION_MESSAGE); //#of eggs purchased, #of dozens, # of single units //all declared as integers numberOfEggsPurchased = Integer.parseInt(howManyEggs); int numberOfDozens, numberOfUnitEggs; //how many dozens are in the quantity purchased? numberOfDozens = numberOfEggsPurchased / 12; //how many single units are left after getting the 3 of dozens in the purchase?
  • 12. numberOfUnitEggs = numberOfEggsPurchased % 12; //amount paid for the # of dozens portion. costForDozens = numberOfDozens * PRICE_PER_DOZEN; //amount paid for the single eggss portion costForUnits = numberOfUnitEggs * PRICE_PER_UNIT_EGGS; //below is the total amount paid in $ totalAmount = costForDozens + costForUnits; //information displayed in the dialog box upon execution of the program. JOptionPane.showMessageDialog(null, " You ordered " + howManyEggs + " eggs. That is " + numberOfDozens + " dozens at $3.25 per dozen and " + numberOfUnitEggs + " egg(s) at 45.0 cents each for a total of $" + totalAmount ); } }
  • 13. Page 50 Game Question Write a Java application that displays two dialog boxes in sequence. The first asks you to think of a number between 1 and 10. The second displays a randomly generated number; the user can see whether his or her guess was accurate. (In future chapters you will improve this game so that the user can enter a guess and the program can determine whether the user was correct. If you wish, you also can tell the user how far off the guess was, whether the guess was high or low, and provide a specific number of repeat attempts.) Save the file as RandomGuess.java. import javax.swing.JOptionPane; public class RandomGuess { public static void main(String [] args) { String newNumber; //the user guess a number declared as astring variable above //the system asks you to think of any number from 1 to 9 JOptionPane.showMessageDialog(null,"Think of any number from 1 to 9 "); //User enters the number into a dialog box newNumber = JOptionPane.showInputDialog(null, "Enter your Guess number here "); //the computer displays a randomly generated number JOptionPane.showMessageDialog(null,"The number guess is " + (1 + (int)(Math.random() * 10))); } }
  • 14. Book Example on Page 137 import java.util.Scanner; public class ParadiseInfo2 { public static void main(String[] args) { double price; double discount; double savings; Scanner keyboard = new Scanner(System.in); System.out.print("Enter cutoffprice for discount >> " ); price = keyboard.nextDouble(); System.out.print("Enter discount rate as awhole number >> "); discount = keyboard.nextDouble(); savings = computeDiscountInfo(price, discount); displayInfo(); System.out.println("Special this week on any order over " + price); System.out.println("Discount of " + discount + " percent "); System.out.println("That's a savings of at least $" + savings); } public static void displayInfo() { System.out.println("Paradise Day Spa wants to pamper you,"); System.out.println("We will make you look good."); } public static double computeDiscountInfo(double pr, double dscnt) { double savings; savings = pr * dscnt/100; return savings; } } Below is the output generated when this class is executed in NetBeans7
  • 15. //this creates a class to store information about services offered at Paradise Spa public class SpaService { // two private data fields that will hold data about spa service private String serviceDescription; private double price; //Within the class’s curly braces and after the field declarations, enter the //following two methods that set the field values. The setServiceDescription() //method accepts a String parameter and assigns it to the serviceDescription //field for each object that eventually will be instantiated. Similarly, the setPrice() method accepts a double parameter and assigns it to the price field. Note that neither of these methods is static. public void setServiceDescription(String service){ serviceDescription = service; } public void setPrice(double pr) { price = pr; } //Next, add two methods that retrieve the field values as follows: public String getServiceDescription() { return serviceDescription; } public double getPrice() { return price; }
  • 16. } //Save the file as SpaService.java, compile it, and then correct any syntax //errors. Remember, you cannot run this file as a program because it does not //contain a public static main() method. After you read the next section, you //will use this class to create objects.
  • 17. This class runs along with the previous class to give the output below when ran on NetBeans8.1 //Open a new file in your text editor, and type the import statement needed for //an interactive program that accepts user keyboard input: import java.util.Scanner; //Create the shell for a class named CreateSpaServices: public class CreateSpaServices { //Between the curly braces of the CreateSpaServices class, create the shell //for a main() method for the application: public static void main(String[] args) { //Within the main() method, declare variables to hold a service description and //price that a user can enter from the keyboard: String service; double price; //Next, declare three objects. Two are SpaService objects that use the class you created in the prior set of “You Do It” steps. The third object uses the built-in Java Scanner class. Both classes use the new operator to allocate memory for their objects, and both call a constructor that has the same name as the class. The difference is that the Scanner constructor requires an argument (System.in), but the SpaService class does not. SpaService firstService = new SpaService(); SpaService secondService = new SpaService(); Scanner keyboard = new Scanner(System.in); //In the next statements, you prompt the user for a service, accept it from the //keyboard, prompt the user for a price, and accept it from the keyboard. System.out.print("Enter service >> "); service = keyboard.nextLine(); System.out.print("Enter price >> "); price = keyboard.nextDouble();
  • 18. //Recall that the setServiceDescription() method in the SpaService class is //nonstatic, meaning it is used with an object, and that it requires a String //argument. Write the statement that sends the service the user entered to the //setServiceDescription() method for the firstService object: firstService.setServiceDescription(service); //Similarly, send the price the user entered to the setPrice() method for the //firstService object. Recall that this method is nonstatic and requires a double //argument. firstService.setPrice(price); //Make a call to the nextLine() method to remove the Enter key that remains in //the input buffer after the last numeric entry. Then repeat the prompts, and //accept data for the second SpaService object. keyboard.nextLine(); System.out.print("Enter service >> "); facialservice = keyboard.nextLine(); System.out.print("Enter price >> "); price = keyboard.nextDouble(); secondService.setServiceDescription(service); secondService.setPrice(price); //Display the details for the firstService object. System.out.println("First service details:"); System.out.println(firstService.getServiceDescription() + " " + "$" + firstService.getPrice()); //Display the details for the secondService object. System.out.println("Second service details:"); System.out.println(secondService.getServiceDescription() + " $" + secondService.getPrice()); //Save the file as CreateSpaServices.java. Compile and execute the program. //Figure 3-31 shows a typical execution. Make sure you understand how the user’s
  • 19. //entered values are assigned to and retrieved from the two SpaService objects. } } } }
  • 20. CHAPTER 3 QUESTIONS 3a. Create an application named ArithmeticMethods whose main() method holds two integer variables. Assign values to the variables. In turn, pass each value to methods named displayNumberPlus10(), displayNumberPlus100(), and displayNumberPlus1000(). Create each method to perform the task its name implies. Save the application as ArithmeticMethods.java. C:UsersChristopherDocumentsNetBeansProjectsJRVampedsrcArithmeticMethods.java // This class receives two numbers and then display the result // of adding 10, 100 and 1000 to them in turn. public class ArithmeticMethods { public static void main(String[] args) { // Two integers 13 and 31 are declared. These are passed as arguments // to each of th three methods that follows int firstNumber = 13; int secondNumber = 31; System.out.println("The number pairs " + firstNumber + " and " + secondNumber); // The main class above implements each of the three arithmetic methods below // in turn. Note that each of these classes are placed outside the main class above. displayNumberPlus10(firstNumber, secondNumber); displayNumberPlus100(firstNumber, secondNumber); displayNumberPlus1000(firstNumber, secondNumber); } // The first method, displayNumberPlus10 public static void displayNumberPlus10(int firstNumber, int secondNumber) { int firstNumberPlus10, secondNumberPlus10; firstNumberPlus10 = firstNumber + 10; secondNumberPlus10 = secondNumber + 10; System.out.println("displayNumberPlus10 is: " + firstNumberPlus10 + " and " + secondNumberPlus10); } // The second method, displayNumberPlus100 public static void displayNumberPlus100(int firstNumber, int secondNumber) { int firstNumberPlus100, secondNumberPlus100; firstNumberPlus100 = firstNumber + 100; secondNumberPlus100 = secondNumber + 100; System.out.println("displayNumberPlus10 is: " + firstNumberPlus100 + " and " + secondNumberPlus100); } // The third method, displayNumberPlus1000 public static void displayNumberPlus1000(int firstNumber, int secondNumber)
  • 21. { int firstNumberPlus1000, secondNumberPlus1000; firstNumberPlus1000 = firstNumber + 1000; secondNumberPlus1000 = secondNumber + 1000; System.out.println("displayNumberPlus10 is: " + firstNumberPlus1000 + " and " + secondNumberPlus1000); } }
  • 22. 3b. Modify the ArithmeticMethods class to accept the values of the two integers from a user at the keyboard. Save the file as ArithmeticMethods2.java. C:UsersChristopherDocumentsNetBeansProjectsJRVampedsrcArithmeticMethods2.java /* * The previous problem is modified so that user can enter any two numbers */ // Add the import statement for user keyboard entry import java.util.Scanner; // The main class receives two numbers and display the result of adding // 10, 100 and 1000 to them in turn public class ArithmeticMethods2 { public static void main(String[] args) { // Two integers are declared int firstNumber, secondNumber; //For user keyboard entry Scanner keyboard = new Scanner(System.in); // input firstNumber System.out.println("Enter the first number:>> "); firstNumber = keyboard.nextInt(); // input secondNumber System.out.println("Enter the second number:>> "); secondNumber = keyboard.nextInt(); // Display the numbers System.out.println("First number is: " + firstNumber + "; Second number is: " + secondNumber); // The following 3 methods are implemented by the main class for each of // the subsequent additions displayNumberPlus10(firstNumber, secondNumber); displayNumberPlus100(firstNumber, secondNumber); displayNumberPlus1000(firstNumber, secondNumber); } // This is the first method public static void displayNumberPlus10(int firstNumber, int secondNumber) { int firstNumberPlus10, secondNumberPlus10; firstNumberPlus10 = firstNumber + 10; secondNumberPlus10 = secondNumber +10; System.out.println("displayNumberPlus10 is: " + firstNumberPlus10 + " and " + secondNumberPlus10); } // This is the second method public static void displayNumberPlus100(int firstNumber, int secondNumber)
  • 23. { int firstNumberPlus100, secondNumberPlus100; firstNumberPlus100 = firstNumber + 100; secondNumberPlus100 = secondNumber +100; System.out.println("displayNumberPlus100 is: " + firstNumberPlus100 + " and " + secondNumberPlus100); } // This is the third method public static void displayNumberPlus1000(int firstNumber, int secondNumber) { int firstNumberPlus1000, secondNumberPlus1000; firstNumberPlus1000 = firstNumber + 1000; secondNumberPlus1000 = secondNumber +1000; System.out.println("displayNumberPlus1000 is: " + firstNumberPlus1000 + " and " + secondNumberPlus1000); } }
  • 24. Modify the ArithmeticMethods class to accept the values of the two integers from a user at the keyboard. Save the file as ArithmeticMethodsInteractive.java. C:UsersChristopherDocumentsNetBeansProjectsJRVampedsrcArithmeticMethodsInteractive.java import javax.swing.JOptionPane; // For dialog box input and output // This class receives two integer numbers and display the result of // adding 10, 100 and 1000 to them in that order public class ArithmeticMethodsInteractive { public static void main(String[] args) { int firstNumber, secondNumber; String numberOne, numberTwo; // needed to enter numbers as Strings // in the JOptionPane numberOne = JOptionPane.showInputDialog(null, "First Number", "Enter the first number", JOptionPane.INFORMATION_MESSAGE); // the number entered into the dialog box above is a String. It needs to be // parsed into an integer before arithmetic operations can be done on it. firstNumber = Integer.parseInt(numberOne); numberTwo = JOptionPane.showInputDialog(null, "Second Number", "Enter the Second number", JOptionPane.INFORMATION_MESSAGE); secondNumber = Integer.parseInt(numberTwo); // The main() class above implements each of the 3 methods below. displayNumberPlus10(firstNumber, secondNumber); displayNumberPlus100(firstNumber, secondNumber); displayNumberPlus1000(firstNumber, secondNumber); } // This is the first method public static void displayNumberPlus10(int firstNumber, int secondNumber) { int firstNumberPlus10, secondNumberPlus10; firstNumberPlus10 = firstNumber + 10; secondNumberPlus10 = secondNumber +10; // The results of the above addition are displayed in a dialog box JOptionPane.showMessageDialog(null, "firstNumberPlus10 is: " + firstNumberPlus10 + " and " + secondNumberPlus10); } // This is the second method public static void displayNumberPlus100(int firstNumber, int secondNumber) { int firstNumberPlus100, secondNumberPlus100; firstNumberPlus100 = firstNumber + 100; secondNumberPlus100 = secondNumber +100; // The results of the above addition are displayed in a dialog box JOptionPane.showMessageDialog(null, "firstNumberPlus10 is: " + firstNumberPlus100 + " and " + secondNumberPlus100); }
  • 25. // This is the third method public static void displayNumberPlus1000(int firstNumber, int secondNumber) { int firstNumberPlus1000, secondNumberPlus1000; firstNumberPlus1000 = firstNumber + 1000; secondNumberPlus1000 = secondNumber +1000; // The results of the above addition are displayed in a dialog box JOptionPane.showMessageDialog(null, "firstNumberPlus10 is: " + firstNumberPlus1000 + " and " + secondNumberPlus1000); } }
  • 26. 4. a. Create an application named Percentages whose main() method holds two double variables. Assign values to the variables. Pass both variables to a method named computePercent() that displays the two values and the value of the first number as a percentage of the second one. For example, if the numbers are 2.0 and 5.0, the method should display a statement similar to “2.0 is 40% of 5.0.” Then call themethod a second time, passing the values in reverse order. Save the application as Percentages.java. C:UsersChristopherDocumentsNetBeansProjectsJRVampedsrcPercentage.java public class Percentage { public static void main(String[] args) { double numFirst = 2.0; double numSecond = 5.0; computePercent(numFirst, numSecond); // This method compute percentages } public static void computePercent(double numFirst, double numSecond) { double firstPercentSecond; // First number as a percentage of second double secondPercentFirst; // Second number as a percentage of first firstPercentSecond = 100 * numFirst/numSecond; secondPercentFirst = 100 * numSecond/numFirst; // Display the results System.out.println(numFirst + " is " + firstPercentSecond + "% of " + numSecond); System.out.println(numSecond + " is " + secondPercentFirst + "% of " + numFirst); } }
  • 27. b. Modify the Percentages class to accept the values of the two doubles from a user at the keyboard. Save the file as Percentages2.java. C:UsersChristopherDocumentsNetBeansProjectsJRVampedsrcPercentages2.ja va /* This application expresses the first number entered as a percentage of the second and also the second number entered as a percentage of the first. */ import java.util.Scanner; public class Percentages2 { public static void main(String[] args) { double numFirst, numSecond; Scanner keyboard = new Scanner(System.in); // Input the first number System.out.println("Enter the first number: "); numFirst = keyboard.nextInt(); // Input the second number System.out.println("Enter the second number: "); numSecond = keyboard.nextInt(); // the main method now calls the method that compute percentages computePercent(numFirst, numSecond); } // the numbers entered from the above are now passed // to the computePercent() method below public static void computePercent(double numFirst, double numSecond) { double firstPercentSecond, secondPercentFirst; // % values to be computed firstPercentSecond = 100 * numFirst/numSecond; secondPercentFirst = 100 * numSecond/numFirst; // Display the results of the above calculation System.out.println(numFirst + " is " + firstPercentSecond + "% of " + numSecond); System.out.println(numSecond + " is " + secondPercentFirst + "% of " + numFirst); } }
  • 29. INTERACTIVE VERSION (PercentageInteractive.java) C:UsersChristopherDocumentsNetBeansProjectsJRVampedsrcPercentageInteractive.va // Interactive version of previous problem import javax.swing.JOptionPane; // Needed for dialog box input and output public class PercentageInteractive { public static void main(String[] args) { double numFirst, numSecond; // Declare two double variables String numberOne, numberTwo; // numbers as Strings into dialog box // input first number numberOne = JOptionPane.showInputDialog(null, "First Number", "Enter the first number", JOptionPane.INFORMATION_MESSAGE); numFirst = Integer.parseInt(numberOne); // input second number numberTwo = JOptionPane.showInputDialog(null, "Second Number", "Enter the second number", JOptionPane.INFORMATION_MESSAGE); numSecond = Integer.parseInt(numberTwo); // The main() class calls the computePercent() method computePercent(numFirst, numSecond); } // the numbers entered above are now parsed to the computePercent() method public static void computePercent(double numFirst, double numSecond) { double firstPercentSecond, secondPercentFirst; firstPercentSecond = 100 * numFirst/numSecond; secondPercentFirst = 100 * numSecond/numFirst; // the results of the computePercent method are displayed in the next // two message boxes JOptionPane.showMessageDialog(null, numFirst + " is " + firstPercentSecond + "% of " + numSecond); JOptionPane.showMessageDialog(null, numSecond + " is " + secondPercentFirst + "% of " + numFirst); } }
  • 30. There are 2.54 centimeters in an inch, and there are 3.7854 liters in a U.S. gallon. 6. Create a class named MetricConversion. Its main() method accepts an integer value from a user at the keyboard, and in turn passes the entered value to two methods. One converts the value from inches to centimeters and the other converts the same value from gallons to liters. Each method displays the results with appropriate explanation. Save the application as MetricConversion.java. C:UsersChristopherDocumentsNetBeansProjectsJRVampedsrcMetricConversion.java import java.util.Scanner; public class MetricConversion { public static void main(String[] args) { // The value to convert is entered as a double double valueToConvert; Scanner keyboard = new Scanner(System.in); // This value is entered fro the keyboard System.out.print("Enter the value to convert:>> "); valueToConvert = keyboard.nextDouble(); // Next, the main method invoke the two methods that // carrry out the conversion inchesToCm(valueToConvert); gallonsToLitres(valueToConvert); } // The inchesToCm() method public static void inchesToCm(double valueToConvert) { final double INCHES_TO_CM = 2.54; double lengthInCm = valueToConvert * INCHES_TO_CM; System.out.println(valueToConvert + " inches = " + lengthInCm + " cm"); } // The gallonsToLitres() method public static void gallonsToLitres(double valueToConvert) { final double GALLONS_TO_LITRES = 3.7854; double volInLitres = valueToConvert * GALLONS_TO_LITRES; System.out.println(valueToConvert + " gallons = " + volInLitres + " litres"); } }
  • 31. Q7. Assume that a gallon of paint covers about 350 square feet of wall space. Create an application with a main() method that prompts the user for the length, width, and height of a rectangular room. Pass these three values to a method that does the following:  Calculates the wall area for a room  Passes the calculated wall area to another method that calculates and returns the number of gallons of paint needed  Displays the number of gallons needed  Computes the price based on a paint price of $32 per gallon, assuming that the painter can buy any fraction of a gallon of paint at the same price as a whole gallon  Returns the price to the main() method The main() method displays the final price. For example, the cost to paint a 15- by-20- foot room with 10-foot ceilings is $64. Save the application as PaintCalculator.java. C:UsersChristopherDocumentsNetBeansProjectsJRVampedsrcPaintCalculator.java /* NOTE: TOTAL WALL AREA OF A ROOM IS 2*(LENGTH * WIDTH + LENGTH * HEIGHT + WIDTH * HEIGHT) NOTE THAT THE FLOOR AND THE CEILING NEED NO PAINTING THEREFORE, TOTAL WALL AREA TO BE PAINTED IS 2 * (LENGTH * WIDTH + WIDTH * HEIGHT) */ import java.util.Scanner; public class PaintCalculator { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.print("Enter the length in feet:>> "); double length = input.nextDouble(); System.out.print("Enter the width in feet:>> "); double width = input.nextDouble(); System.out.print("Enter the height in feet:>> "); double height = input.nextDouble(); System.out.println(); // Declare variables associated with the totalWallArea computation double wallsArea; // Total Wall Area double volGallons; // Voulme of paint needed double costs; // Cost of painting the walls // Method that computes total wall area wallsArea = computeTotalWallArea(length, width, height); final double SQFT_PER_GALLON = 350;
  • 32. volGallons = wallsArea/SQFT_PER_GALLON; final double COST_PER_GALLON = 32; // Cost per gallon double cost; // Cost to pain the walls. cost = volGallons * COST_PER_GALLON; System.out.println("Gallons needed is:>> " + volGallons + " gals "); System.out.println("Total cost for painting wall of " + length + " ft by " + width + " ft by " + height + " ft is:>> $" + cost); } public static double computeTotalWallArea(double length, double width, double height) { double totalWallArea; totalWallArea = 2 * (length * height + width * height); System.out.println("The total wall area is: " + totalWallArea + " sq.ft"); return totalWallArea; } }
  • 33. 8. The Harrison Group Life Insurance company computes annual policy premiums based on the age the customer turns in the current calendar year. The premium is computed by taking the decade of the customer’s age, adding 15 to it, and multiplying by 20. For example, a 34-year-old would pay $360, which is calculated by adding the decades (3) to 15, and then multiplying by 20. Write an application that prompts a user for the current year and a birth year. Pass both to a method that calculates and returns the premium amount, and then display the returned amount. Save the application as Insurance.java. C:UsersChristopherDocumentsNetBeansProjectsJRVampedsrcInsurance.java /* * IN THIS APP, THE OLDER YOU ARE, THE MORE. * YOU PAY FOR INSURANCE */ import java.util.Scanner; public class Insurance { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.print("Enter the year you were born:>> "); int birthYear = input.nextInt(); System.out.print("Enter the current year:>> "); int currentYear = input.nextInt(); //Call the method that computes the applicable insurance premium computePremiumAmount(birthYear, currentYear); } public static int computePremiumAmount(int birthYear, int currentYear) { int premiumAmount, decadeYears; final int DECADE_FACTOR = 10; final int YEAR_ADD_ON = 15; final int MULTIPLIER = 20; decadeYears = (currentYear - birthYear) / DECADE_FACTOR; premiumAmount = (decadeYears + YEAR_ADD_ON) * MULTIPLIER; System.out.println("Total premium is:>> $" + premiumAmount); return premiumAmount; } }
  • 34. 9. Write an application that calculates and displays the weekly salary for an employee. The main() method prompts the user for an hourly pay rate, regular hours, and overtime hours. Create a separate method to calculate overtime pay, which is regular hours times the pay rate plus overtime hours times 1.5 times the pay rate; return the result to the main() method to be displayed. Save the program as Salary.java. C:UsersChristopherDocumentsNetBeansProjectsJRVampedsrcSalary.java import java.util.Scanner; public class Salary { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.print("Enter the # of hours of regular work:>> "); double regularHours = input.nextDouble(); System.out.print("Enter the regular hourly rate:>> "); double regularRate = input.nextDouble(); System.out.print("Enter the # of hours of overtime work:>> "); double overtimeHours = input.nextDouble(); // Call the method that computes the total pay below totalPay(regularHours, regularRate, overtimeHours); } public static double totalPay(double regularHours, double regularRate, double overtimeHours) { double totalPay; totalPay = regularHours * regularRate + overtimeHours * regularRate * 1.5; System.out.println("Total pay is:>> $" + totalPay); return totalPay; } }
  • 35. 10. Write an application that calculates and displays the amount of money a user would have if his or her money could be invested at 5 percent interest for one year. Create a method that prompts the user for the starting value of the investment and returns it to the calling program. Call a separate method to do the calculation, and return the result to be displayed. Save the program as Interest.java. C:UsersChristopherDocumentsNetBeansProjectsJRVampedsrcInterest.java import java.util.Scanner; public class Interest { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.print("Enter the starting amount:>> "); double principal = input.nextDouble(); System.out.print("Enter the interest rate:>> "); double rate = input.nextDouble(); System.out.print("Enter the number of years:>> "); int time = input.nextInt(); // The main() method now calls the method that calculates // the amount amount(principal, rate, time); } public static double amount(double principal, double rate, int time) { double amount = principal * (1 + rate * time/100); System.out.println("The amount is:>> $" + amount); return amount; } }
  • 36. 11. a. Create a class named Sandwich. Data fields include a String for the main ingredient (such as “tuna”), a String for bread type (such as “wheat”), and a double for price (such as 4.99). Include methods to get and set values for each of these fields. Save the class as Sandwich.java. b. Create an application named TestSandwich that instantiates one Sandwich object and demonstrates the use of the set and get methods. Save this application as TestSandwich.java. /*Note that this class, Sandwich, cannot run on its own. It doesn't have a main method It must be in the same folder as the TestSandwich folder for the latter to run */ C:UsersChristopherDocumentsNetBeansProjectsJRVampedsrcSandwich.java public class Sandwich { //Insert three private data fields private double price; private String mainIngredient; private String breadType; /** * The following three methods set the fields values * The first method is for the mainIngredient * The second method is for the breadType * The third method is for the price */ // Mutator methods public void setMainIngredient(String ingredient) { mainIngredient = ingredient; } public void setBreadType(String type) { breadType = type; } public void setPrice(double pr) { price = pr; } /** * The following three methods get the fields values * The first method is for the mainIngredient * The second method is for the breadType * The third method is for the price */ // Accessor methods public String getMainIngredient() { return mainIngredient;
  • 37. } public String getBreadType() { return breadType; } public double getPrice() { return price; } } /*Note that this class, TestSandwich, must be in the same folder as the Sandwhich class for it to run*/ C:UsersChristopherDocumentsNetBeansProjectsJRVampedsrcTestSandwich.java import java.util.Scanner; public class TestSandwich { public static void main(String[] args) { // Declare variables to hold the sandwich type, bread type // the price that customers pay per sandwich String ingredient; String type; double price; /** * Next, create three objects that uses the previously created Sandwich class. The three objects are for the sandwich type and the built in Java class. All the three classes use the new operator to allocate memory for their new objects. Each of the new classes call a constructor that has the same name as the class Sandwich. The difference is that the Scanner class requires an argument (System.in) but the Sandwich class does not. */ Sandwich sandwichType = new Sandwich(); Sandwich breadType = new Sandwich(); Scanner keyboard = new Scanner(System.in); /** * The next statements prompts the user to enter the type of sandwich, bread type and * price in that order. */ System.out.print("Enter the type of sandwich:>> "); ingredient = keyboard.nextLine(); System.out.print("Enter the type of bread used:>> ");
  • 38. type = keyboard.nextLine(); System.out.print("Enter the price:>> "); price = keyboard.nextDouble(); /** * The following three statements send the order the user placed to each of the the three * corresponding methods in Sandwich class. */ sandwichType.setMainIngredient(ingredient); sandwichType.setBreadType(type); sandwichType.setPrice(price); // Final output System.out.println(""); System.out.println("Here is the summary of your order"); System.out.println("--------------------------------------------"); System.out.println("Sandwich type: >> " + sandwichType.getMainIngredient()); System.out.println("Bread type: >>" + sandwichType.getBreadType()); System.out.println("For a total price of:>> $" + sandwichType.getPrice()); } }
  • 39. 12. a. Create a class named Student. A Student has fields for an ID number, number of credit hours earned, and number of points earned. (For example, many schools compute grade point averages based on a scale of 4, so a three-credit-hour class in which a student earns an A is worth 12 points.) Include methods to assign values to all fields. A Student also has a field for grade point average. Include a method to compute the grade point average field by dividing points by credit hours earned. Write methods to display the values in each Student field. Save this class as Student.java. b. Write a class named ShowStudent that instantiates a Student object from the class you created and assign values to its fields. Compute the Student grade point average, and then display all the values associated with the Student. Save the application as ShowStudent.java. c. Create a constructor for the Student class you created. The constructor should initialize each Student’s ID number to 9999, his or her points earned to 12, and credit hours to 3 (resulting in a grade point average of 4.0). Write a program that demonstrates that the constructor works by instantiating an object and displaying the initial values. Save the application as ShowStudent2.java. /*The Student class doesn't have a main method. It must be in the same folder as the ShowStudent class for the latter to run */ C:UsersChristopherDocumentsNetBeansProjectsJRVampedsrcStudent.java public class Student { // Insert three private data fields private int studentIdNumber; private double creditHoursEarned; private double creditPointsEarned; /** * Mutatator methods for setting field values * student's ID number * credit hours earned * credit points earned. */ public void setStudentNumber(int idNumber) { studentIdNumber = idNumber; } public void setCreditHoursEarned(double creditHours) { creditHoursEarned = creditHours; } public void setCreditPointsEarned(double points) { creditPointsEarned = points; }
  • 40. /** * Accessor methods for getting field values: * student's ID number * credit hours earned * credit points earned. */ public int getStudentNumber() { return studentIdNumber; } public double getCreditHoursEarned() { return creditHoursEarned; } public double getCreditPointsEarned() { return creditPointsEarned; } // Default constructor takes no parameters, it has default values public Student() { studentIdNumber = 9999; creditPointsEarned = 12; creditHoursEarned = 3; } } C:UsersChristopherDocumentsNetBeansProjectsJRVampedsrcShowStudent.java import java.util.Scanner; public class ShowStudent { public static void main(String[] args) { // Declare variables for the ID#, creedit hours earned, credit points // earned, grade point average and the Scanner object for user input int idNumber; double creditHoursEarned; double creditPointsEarned; double gradePointAverage; Scanner keyboard = new Scanner(System.in); /** * Create objects that use the previously created Student class. * The object is for a new student (firstStudent). The new operator is used * to allocate memory for the Student object. Both call constructors that has * the same name as the class, Student. */
  • 41. Student firstStudent = new Student(); /** * The following lines prompts the user for the student's ID#, * credit hours earned and total points earned. */ System.out.print("Enter student's ID #:>>> "); idNumber = keyboard.nextInt(); System.out.print("Enter the total credit hours earned:>> "); creditHoursEarned = keyboard.nextInt(); System.out.print("Enter total points earned:>> "); creditPointsEarned = keyboard.nextInt(); // Calculating the grade point average gradePointAverage = creditPointsEarned / creditHoursEarned; /** * The following three methods send the firstStudent data to the * methods created in Student class. The fourth line calls on the * method for calculating gradePointAverage. */ firstStudent.setStudentNumber(idNumber); firstStudent.getCreditPointsEarned(); firstStudent.setCreditPointsEarned(creditPointsEarned); gradePointAverage(creditHoursEarned, creditPointsEarned); // Program execution printout System.out.println(""); System.out.println("Below are student with ID#: " + firstStudent.getStudentNumber() + " Score Details"); System.out.println("Total credit hours earned:>> " + firstStudent.getCreditHoursEarned()); System.out.println("Total credit points earned:>> " + firstStudent.getCreditPointsEarned()); System.out.println("CGPA:>> " + gradePointAverage); //Demonstrating default constructor Student defaultStudent; defaultStudent = new Student(); { int idNum = defaultStudent.getStudentNumber(); double creditHours = defaultStudent.getCreditHoursEarned(); double creditPoints = defaultStudent.getCreditPointsEarned(); //double creditAverage = defaultStudent.getCreditPointsEarned(); gradePointAverage = creditPoints / creditHours; //(creditHours, creditPoints); System.out.println("++++++++++++++++"); System.out.println("Default Student ID# is:>> " + idNum); System.out.println("Default credit hours earned:>> " + creditHours); System.out.println("Default credit points earned:>> " + creditPoints);
  • 42. System.out.println("Default cumulative grade poit average:>> " + gradePointAverage); } } // Method for calculating grade point average. public static double gradePointAverage(double creditHoursEarned, double creditPointsEarned) { double gradePointAverage; gradePointAverage = creditPointsEarned / creditHoursEarned; //System.out.print(gradePointAverage); return gradePointAverage; } }
  • 43. Question 13 Page 174 (Note: Answers not exactly like it was in the text) a. Create a class named BankAccount with fields that hold an account number, the owner’s name, and the account balance. Include a constructor that initializes each field to appropriate default values. Also include methods to get and set each of the fields. Include a method named deductMonthlyFee() that reduces the balance by $4.00. Include a static method named explainAccountPolicy() that explains that the $4 service fee will be deducted each month. Save the class as BankAccount.java. b. Create a class named TestBankAccount whose main() method declares four BankAccount objects. Call a getData() method three times. Within the method, prompt a user for values for each field for a BankAccount, and return a BankAccount object to the main() method where it is assigned to one of main()’s BankAccount objects. Do not prompt the user for values for the fourth BankAccount object, but let it continue to hold the default values. Then, in main(), pass each BankAccount object in turn to a showValues() method that displays the data, calls the method that deducts the monthly fee, and displays the balance again. The showValues() method also calls the method that explains the deduction policy. Save the application as TestBankAccount.java. 13A C:UsersChristopherDocumentsNetBeansProjectsJRVampedsrcNBankAccount.j ava public class NBankAccount { // Data field variable names private int accountNum; private String accountName; private double accountBalance; // The account method that receive parameters in the constructors public NBankAccount(int acctNum, String name, double balance) { this.accountNum = acctNum; this.accountName = name; this.accountBalance = balance; } // The default account method with no parameter in the constructors public NBankAccount() { accountNum = 123456; accountName = "Willy Akinlade"; accountBalance = 00.00; } // The following are the set methods public void setAccountNum(int acctNum) { accountNum = acctNum; }
  • 44. public void setAccountName(String ownersName) { accountName = ownersName; } public void setAccountBalance(double acctBalance) { accountBalance = acctBalance; } // The following are the get methods public int getAccountNum() { return accountNum; } public String getAccountName() { return accountName; } public double getAccountBalance() { return accountBalance; } } 13BC:UsersChristopherDocumentsNetBeansProjectsJRVampedsrcTestNBankAccount.java import java.util.Scanner; public class TestNBankAccount { public static void main(String[] args) { // first account parameters values Scanner keyboard = new Scanner(System.in); System.out.print("Enter firstAccount #:>> "); int accountNum = keyboard.nextInt(); System.out.print("Enter firstAccount owner:>> "); String accountName = keyboard.next(); System.out.print("Enter firstAccount balance:>> $"); double accountBalance = keyboard.nextDouble(); System.out.println(""); // Creating firstAccount object NBankAccount firstAccount; firstAccount = new NBankAccount(accountNum, accountName, accountBalance); {
  • 45. int accountNumber = firstAccount.getAccountNum(); String acctName = firstAccount.getAccountName(); double acctBalance = firstAccount.getAccountBalance(); double newBalance = acctBalance - 4; // Screen output for firstAccount System.out.println("firstAccount #:>> " + accountNumber); System.out.println("firstAccount owner:>> " + acctName); System.out.println("firstAccount balance before deduction:>> $" + acctBalance); System.out.println("firstAccount balance after deduction:>> $" + newBalance); System.out.println(" "); System.out.println("NOTE: A monthly fe of $4.00 is deducted as service fees."); System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~"); } System.out.print(""); // Enter the second account parameter values System.out.print("Enter secondAccount #:>> "); int secAccountNum = keyboard.nextInt(); System.out.print("Enter secondAccount owner:>> "); String secAccountName = keyboard.next(); System.out.print("Enter secondAccount balance:>> $"); double secAccountBalance = keyboard.nextDouble(); System.out.println(" "); // Creating secondAccount object NBankAccount secondAccount; secondAccount = new NBankAccount(secAccountNum, secAccountName, secAccountBalance); { int accountNumber = secondAccount.getAccountNum(); String acctName = secondAccount.getAccountName(); double acctBalance = secondAccount.getAccountBalance(); double newBalance = acctBalance - 4; // Screen output for secondAccount System.out.println("secondAccount #:>> " + accountNumber); System.out.println("secondAccount owner:>> " + acctName); System.out.println("secondAccount balance before defuction:>> $" + acctBalance); System.out.println("secondAccount balance after desduction:>> $" + newBalance); System.out.println("NOTE: A monthly fe of $4.00 is deducted as service fees."); System.out.println(" "); System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~"); } // This is the default account, it returns default values NBankAccount thirdAccount; thirdAccount = new NBankAccount(); {
  • 46. int accountNumber = thirdAccount.getAccountNum(); String acctName = thirdAccount.getAccountName(); double acctBalance = thirdAccount.getAccountBalance(); System.out.println(" "); System.out.println("Default number:>>" + accountNumber); System.out.println("Default owner:>>" + acctName); System.out.println("Default account balance:>> $" + acctBalance); } } }
  • 47. Question 14 page 174, 14. a. Create a class named Painting that contains fields for a painting’s title, artist, medium (such as water color), price, and gallery commission. Create a constructor that initializes each field to an appropriate default value, and create instance methods that get and set the fields for title, artist, medium, and price. The gallery commission field cannot be set from outside the class; it is computed as 20 percent of the price each time the price is set. Save the class as Painting.java. b. Create a class named TestPainting whose main() method declares three Painting items. Create a method that prompts the user for and accepts values for two of the Painting objects, and leave the third with the default values supplied by the constructor. Then display each completed object. Finally, display a message that explains the gallery commission rate. Save the application as TestPainting.java. Painting Class C:UsersChristopherDocumentsNetBeansProjectsJRVampedsrcPainting.java public class Painting { // Private data fields private String title; private String artist; private String medium; private double price; private double commission; // Constructor that receive parameters public Painting(String pTitle, String pArtist, String pMedium, double pCost) { this.title = pTitle; this.artist = pArtist; this.medium = pMedium; this.price = pCost; } // Default constructor takes no parameters, it has default values public Painting() { title = "AAAAA"; artist = "XXXXX"; medium = "ZZZZZ"; price = 25000.00; } // Accessor and mutator methods public String getTitle() { return title; }
  • 48. public void setTitle(String description) { title = description; } public String getArtist() { return artist; } public void setArtist(String theArtist) { artist = theArtist; } public String getMedium() { return medium; } public void setMedium(String media) { medium = media; } public double getPrice() { return price; } public void setPrice(double cost) { price = cost; } public double getCommission() { double commission; commission = 0.2 * this.price; return commission; } } TestPainting main () class C:UsersChristopherDocumentsNetBeansProjectsJRVampedsrcTestPainting.java import java.util.Scanner; public class TestPainting { public static void main(String[] args) { // Create Scanner object for user input of the variables declared above
  • 49. Scanner keyboard = new Scanner(System.in); // Declare the variables that the user will enter into the created object String title; String artist; String medium; double price; System.out.print("Enter painting description:>> "); title = keyboard.next(); System.out.print("Enter the name of artist:>> "); artist = keyboard.next(); System.out.print("Enter the medium used:>> "); medium = keyboard.next(); System.out.print("Enter the painting price:>> $"); price = keyboard.nextDouble(); // Creating first Painting object Painting firstArtWork = new Painting(title, artist, medium, price); { String descr = firstArtWork.getTitle(); String author = firstArtWork.getArtist(); String material = firstArtWork.getMedium(); double cost = firstArtWork.getPrice(); double commission = firstArtWork.getCommission(); System.out.println(" "); System.out.println("Painting title is:>> " + descr); System.out.println("Artist name is:>> " + author); System.out.println("The material used:>> " + material); System.out.println("Cost for the painting:>> $" + cost + "n"); System.out.println("Commission for the painting:>> $" + commission ); System.out.println("NOTE: A 20% sales commission charges apply"); System.out.println("~~~~~~~~~~~~~~"); } // This is the default account, it returns default values Painting defaultArtWork; defaultArtWork = new Painting(); { String description = defaultArtWork.getTitle(); String painter = defaultArtWork.getArtist(); String materl = defaultArtWork.getMedium(); double pricing = defaultArtWork.getPrice(); double commission = defaultArtWork.getCommission(); System.out.println(" "); System.out.println("Default painting is:>>" + description); System.out.println("Default artist is:>>" + painter); System.out.println("Default medium is:>>" + materl); System.out.println("Default price:>> $" + pricing +"n");
  • 50. System.out.println("Commission for the painting:>> $" + commission); System.out.println("NOTE: A 20% sales commission charges apply"); } }}
  • 51. DEMONSTRATING Overloading C:UsersChristopherDocumentsNetBeansProjectsJDMay2018srcDemoOverload.java // This class demonstrates Overloading - Page 197 Joyce Farrel 8th Ed public class DemoOverload { public static void main(String[] args) { int month = 6, day = 24, year = 2015; displayDate(month); displayDate(month, day); displayDate(month, day, year); } // Overloaded method display the month public static void displayDate(int mm) { System.out.println("Event date " + mm + "/1/2014"); } // Overloaded method display the month and day public static void displayDate(int mm, int dd) { System.out.println("Event date " + mm + "/" + dd + "/2014"); } // Overloaded method display the month and day and year public static void displayDate(int mm, int dd, int yy) { System.out.println("Event date " + mm + "/" + dd + "/" + yy); } }
  • 52. C:UsersChristopherDocumentsNetBeansProjectsJRVampedsrcCarInsurancePolicy.java /* Open a new file in your text editor, and start the CarInsurancePolicy class as follows. The class contains three fields that hold a policy number, the number of payments the policyholder will make annually, and the policyholder’s city of residence. */ public class CarInsurancePolicy { private int policyNumber; private int numPayments; private String residentCity; // Create a constructor that requires parameters for all three data fields public CarInsurancePolicy(int num, int payments, String city) { policyNumber = num; numPayments = payments; residentCity = city; } /* Suppose the agency that sells car insurance policies is in the city of Mayfield. Create a two-parameter constructor that requires only a policy number and the number of payments. This constructor assigns Mayfield to residentCity. */ public CarInsurancePolicy(int num, int payments) { policyNumber = num; numPayments = payments; residentCity = "Port Harcourt"; } /* Add a third constructor that requires only a policy number parameter. This constructor uses the default values of two annual payments and Mayfield as the resident city. (Later in this chapter, you will learn how to eliminate the duplicated assignments in these constructors.) */ public CarInsurancePolicy(int num) { policyNumber = num; numPayments = 2; residentCity = "Port Harcourt"; } /* Add a display() method that outputs all the insurance policy data: */ public void display() { System.out.println("Policy #" + policyNumber + ". " + numPayments + " payments annually. Driver resides in " + residentCity + "."); } }
  • 53. C:UsersChristopherDocumentsNetBeansProjectsJRVampedsrcCreatedPolicies.java /* Open a new text file to create a short application that demonstrates the constructors at work. The application declares three CarInsurancePolicy objects using a different constructor version each time. Type the following code: */ public class CreatedPolicies { public static void main(String[] args) { CarInsurancePolicy first = new CarInsurancePolicy(123); CarInsurancePolicy second = new CarInsurancePolicy(456, 4); CarInsurancePolicy third = new CarInsurancePolicy (789, 12, "Port Harcourt"); // Display each object, and add closing curly braces for the method // and the class: first.display(); second.display(); third.display(); } }
  • 54. Example demonstrating the creation of classes and instantiating objects from them. The Employee class below with four data fields and the methods for getting and setting data into the fields package MyJavaLab; public class Employee { private int empNum; //These are the data fields for the Employee Class private String empLastName; private String empFirstName; private double empSalary; public int getEmpNum() //These are the methods for setting and retrieving data { //from the fields in Employee class return empNum; } public void setEmpNum(int empNo) { empNum = empNo; } public String getEmpLastName() { return empLastName; } public void setEmpLastName(String lastName) { empLastName = lastName; } public String getEmpFirstName()
  • 55. { return empFirstName; } public void setEmpFirstName(String firstName) { empFirstName = firstName; } public double getEmpSalary() { return empSalary; } public void setEmpSalary(double salary) { empSalary = salary; } } The class below instantiate objects (md and bdc) of the Employee class and access the Employee class methods using the identifier, a dot and a method call (to call the methods in the Employee class). package MyJavaLab; public class EmployeesExample { public static void main(String[] args) { Employee md = new Employee(); //The Employee MD Employee bdc = new Employee(); //The Employee is BDC md.setEmpNum(345); bdc.setEmpNum(456); md.setEmpLastName("Akinlade");
  • 56. md.setEmpFirstName("Christopher"); bdc.setEmpLastName("Kolawole"); bdc.setEmpFirstName("Michael"); md.setEmpSalary(56408.55); System.out.println("The MD's employee # is : " + md.getEmpNum()); System.out.println("The MD's name is " + md.getEmpLastName() + " " + md.getEmpFirstName()); System.out.println("And his starting salary is $" + md.getEmpSalary()); System.out.println(""); System.out.println("The BDC's employee # is : " + bdc.getEmpNum()); System.out.println("The BDC's name is " + bdc.getEmpLastName() + " " + bdc.getEmpFirstName()); System.out.println("And his starting salary is $" + bdc.getEmpSalary()); } }
  • 57. CREATING CLASSES, DECLARING & USING OBJECTS SECTION1: Creating a Class That Contains Instance Fields and Methods In this section, you create a class to store information about event services offered at Paradise Day Spa. 1. Open a new document in your text editor, and type the following class header and the curly braces to surround the class body: public class SpaServices { } 2. Between the curly braces for the class, insert two private data fields that will hold data about a spa service: private String serviceDescription; private double price; 3. Within the class’s curly braces and after the field declarations, enter the following two methods that set the field values. The setServiceDescription() method accepts a String parameter and assigns it to the serviceDescription field for each object that eventually will be instantiated. Similarly, the setPrice() method accepts a double parameter and assigns it to the price field. Note that neither of these methods is static. public void setServiceDescription(String service)
  • 58. { serviceDescription = service; } public void setPrice(double pr) { price = pr; } 4. Next, add two methods that retrieve the field values as follows: public String getServiceDescription() { return serviceDescription; } public double getPrice() { return price; } 5. Save the file as SpaServices.java, compile it, and then correct any syntax errors. Remember, you cannot run this file as a program because it does not contain a public static main() method. In the next section, this class is used to create objects. SECTION 2 Declaring and Using Objects In section 1, you created a class named SpaServices. Now you create an application that instantiates and uses SpaServices objects. 1. Open a new file in your text editor, and type the import statement needed for an interactive program that accepts user keyboard input: import java.util.Scanner;
  • 59. 2. Create the shell for a class named CreateSpaServices: public class CreateSpaServices { } 3. Between the curly braces of the CreateSpaServices class, create the shell for a main() method for the application: public static void main(String[] args) { } 4. Within the main() method, declare variables to hold a service description and price that a user can enter from the keyboard: String service; double price; 5. Next, declare three objects. Two are SpaService objects that use the class you created in the prior set of “You Do It” steps. The third object uses the built- in Java Scanner class. Both classes use the new operator to allocate memory for their objects, and both call a constructor that has the same name as the class. The difference is that the Scanner constructor requires an argument (System.in), but the SpaService class does not. SpaServices firstService = new SpaService(); SpaServices secondService = new SpaService(); Scanner keyboard = new Scanner(System.in); 6. In the next statements, you prompt the user for a service, accept it from the keyboard, prompt the user for a price, and accept it from the keyboard.
  • 60. System.out.print("Enter first service >> "); service = keyboard.nextLine(); System.out.print("Enter price >> "); price = keyboard.nextDouble(); 7. Recall that the setServiceDescription() method in the SpaService class is nonstatic, meaning it is used with an object, and that it requires a String argument. Write the statement that sends the service the user entered to the setServiceDescription() method for the firstService object: firstService.setServiceDescription(service); 8. Similarly, send the price the user entered to the setPrice() method for the firstService object. Recall that this method is nonstatic and requires a double argument. firstService.setPrice(price); 9. Make a call to the nextLine() method to remove the Enter key that remains in the input buffer after the last numeric entry. Then repeat the prompts, and accept data for the second SpaServices object. keyboard.nextLine(); System.out.print("Enter second service >> "); service = keyboard.nextLine(); System.out.print("Enter price >> "); price = keyboard.nextDouble(); secondService.setServiceDescription(service); secondService.setPrice(price); 10. Display the details for the firstService object.
  • 61. System.out.println("First service details:"); System.out.println(firstService.getServiceDescription() + " $" + firstService.getPrice()); 11. Display the details for the secondService object. System.out.println("Second service details:"); System.out.println(secondService.getServiceDescription() + " $" + secondService.getPrice()); 12. Save the file as CreateSpaServices.java. Compile and execute the program. The figure below shows a typical execution. Make sure you understand how the user’s entered values are assigned to and retrieved from the two SpaService objects.
  • 62. Q1 – Page 234. Create a class named FormLetterWriter that includes two overloaded methods named displaySalutation(). The first method takes one String parameter that represents a customer’s last name, and it displays the salutation “Dear Mr. or Ms.”followed by the last name. The second method accepts two String parameters that represent a first and last name, and it displays the greeting “Dear” followed by the first name, a space, and the last name. After each salutation, display the rest of a short business letter: “Thank you for your recent order.” Write a main() method that tests each overloaded method. Save the file as FormLetterWriter.java. C:UsersChristopherDocumentsNetBeansProjectsJRVampedsrcFormLetterWriter.java public class FormLetterWriter { public static void main(String[] args) { // Declair two String variables String firstName = "Mfon"; String lastName = "Akinlade"; // The first overloaded method call displaySalutation(lastName); // The second overloaded method call displaySalutation(firstName, lastName); System.out.println("Thanks for your order. "); } // First overloaded method public static void displaySalutation(String firstName) { System.out.println("Dear Mr. or Ms. " + firstName); } // Second overloaded method public static void displaySalutation(String firstName, String lastName) { System.out.println("Dear " + firstName + " " + lastName); } }
  • 63. Q2 page 235. Create a class named Billing that includes three overloaded computeBill() methods for a photo book store.  When computeBill() receives a single parameter, it represents the price of one photo book ordered. Add 8% tax, and return the total due.  When computeBill() receives two parameters, they represent the price of a photo book and the quantity ordered. Multiply the two values, add 8% tax, and return the total due.  When computeBill() receives three parameters, they represent the price of a photo book, the quantity ordered, and a coupon value. Multiply the quantity and price, reduce the result by the coupon value, and then add 8% tax and return the total due. Write a main() method that tests all three overloaded methods. Save the application as Billing.java. C:UsersChristopherDocumentsNetBeansProjectsJRVampedsrcBilling.java public class Billing { public static void main(String[] args) { //Declare three variables double price; double couponValue; int qty; // the variable values below will be used to test the // overloaded methods price = 100.00; qty = 100; couponValue = 200; // The three overloaded methods totalBill(price); totalBill(price, qty); totalBill(price, qty, couponValue); } // First Overlaoded method with price as single argument public static void totalBill(double price) { double totalDue; double taxPaid; taxPaid = 8 * price / 100; totalDue = price + taxPaid; System.out.println("You ordered 1 copy, Cost = $" + totalDue + " Inclusive Sales Tax: = $" + taxPaid); } // Second Overlaoded method with price and quantity as arguments public static void totalBill(double price, int qty) { double percentTax; double preTaxAmount; double totalDue; double taxPaid;
  • 64. preTaxAmount = price * qty; taxPaid = 8 * preTaxAmount / 100; totalDue = preTaxAmount + taxPaid; System.out.println("You ordered " + qty + " copies at a Total Cost of" + " $" + totalDue + " Inclusive Sales Tax: = $" + taxPaid); } // Third overloaded method with price, quantity and coupon value as // arguments public static void totalBill(double price, int qty, double couponValue) { double totalDue; double preCouponAmount; double preTaxAmount; double taxPaid; preCouponAmount = price * qty; preTaxAmount = preCouponAmount - couponValue; taxPaid = 8 * preTaxAmount / 100; totalDue = preTaxAmount + taxPaid; System.out.println("You ordered " + qty + " copies, at a Total Cost " + "of = $" + totalDue + ", inclusive Tax: = $" + taxPaid); } }
  • 65. Page 235 (Java Programming – 7th Ed – By Joyce Farrell 3. a. Create a BirdSighting class for the Birmingham Birdwatcher’s Club that includes data fields for a bird species sighted, the number seen, and the day of the year. Forexample, April 1 is the 91st day of the year, assuming it is not a leap year. The classalso includes methods to get each field. In addition, create a default constructor that automatically sets the species to “robin” and the number and day to 1. Save the file as BirdSighting.java. Create an application named TestBirdSighting that demonstrates that each method works correctly. Save the file as TestBirdSighting.java. b. Create an additional overloaded constructor for the BirdSighting class you created in Exercise 3a. This constructor receives parameters for each of the data fields and assigns them appropriately. Add any needed statements to the TestBirdSighting application to ensure that the overloaded constructor works correctly, save it, and then test it. c. Create a class with the same functionality as the BirdSighting class, but create the default constructor to call the three-parameter constructor. Save the class as BirdSighting2.java. Create an application to test the new version of the class and name it TestBirdSighting2.java. //Below is the BirdSighting.java class C:UsersChristopherDocumentsNetBeansProjectsJRVampedsrcBirdSighting.jaa public class BirdSighting { // Declare the private data fields private String species; private int numBirdsSeen; private int dayOfYear; // The default constructor public BirdSighting() { species = "robin"; numBirdsSeen = 1; dayOfYear = 1; } // Constructor and methods that receive values public BirdSighting(String specs, int birdsCount, int day) { species = specs; numBirdsSeen = birdsCount; dayOfYear = day; } // Get methods public String getSpecies() { return species; }
  • 66. public int getNumBirdsSeen() { return numBirdsSeen; } public int getDayOfYear() { return dayOfYear; } // Set methods public void setSpecies(String specs) { species = specs; } public void setNumBirdsSeen(int numOfBirds) { numBirdsSeen = numOfBirds; } public void setDayOfYear(int day) { dayOfYear = day; } } //The TestBirdSighting.java main class that uses the code in the previous section C:UsersChristopherDocumentsNetBeansProjectsJRVampedsrcTestBirdSighting.java import java.util.Scanner; public class TestBirdSighting { public static void main(String[] args) { // Create default BirdSighting object BirdSighting defaultSight = new BirdSighting(); String species = defaultSight.getSpecies(); int numOfBirdsSeen = defaultSight.getNumBirdsSeen(); int dayOfYear = defaultSight.getDayOfYear(); System.out.println("nDEFAULT Bird Sightings with parameters" + " in BirdSighting.java class"); System.out.println(numOfBirdsSeen + " birds of the " + species + " species were seen on the " + dayOfYear + " of the year n"); System.out.println("DETAILS FOR FIRST BIRD SIGHTING"); Scanner keyboard = new Scanner(System.in); System.out.print("Enter the bird species name:>> "); species = keyboard.next(); System.out.print("How many of the species did you see? >> ");
  • 67. numOfBirdsSeen = keyboard.nextInt(); System.out.print("Enter the day of the year:>> "); dayOfYear = keyboard.nextInt(); // Create the first BirdSighting object, firsSight BirdSighting firstSight = new BirdSighting(species, numOfBirdsSeen, dayOfYear); System.out.println("nOn the First Sighting "); System.out.println(numOfBirdsSeen + " birds of the " + species + " species were seen on the " + dayOfYear + " day of the year"); System.out.println(" ~~~~~~~~~~~~~~~~~~~~~~~~~~"); System.out.println("DETAILS FOR SECOND BIRD SIGHTING"); //Scanner keyboard = new Scanner(System.in); System.out.print("Enter the bird species name:>> "); species = keyboard.next(); System.out.print("How many of the species did you see? >> "); numOfBirdsSeen = keyboard.nextInt(); System.out.print("Enter the day of the year:>> "); dayOfYear = keyboard.nextInt(); // Create the first BirdSighting object, firsSight BirdSighting secondSight = new BirdSighting(species, numOfBirdsSeen, dayOfYear); System.out.println("nOn the Second Sighting "); System.out.println(numOfBirdsSeen + " birds of the " + species + " species were seen on the " + dayOfYear + " day of the year"); System.out.println(" ~~~~~~~~~~~~~~~~~~~~~~~~~~"); } }
  • 68. 3c C:UsersChristopherDocumentsNetBeansProjectsJRVampedsrcBirdSighting2.java public class BirdSighting2 { private String species; private int numberSeen; private int dayOfYear; //Method with constructors that take parameters when objects are created public BirdSighting2(String specs, int numSeen, int day) { species = specs; numberSeen = numSeen; dayOfYear = day; } // Get methods public String getSpecies() { return species; } public int getNumberSeen() { return numberSeen; } public int getDayOfYear() { return dayOfYear; } //Set methods public void setSpecies(String specs) { species = specs; } public void setNumberSeen(int numSeen) { numberSeen = numSeen; } public void setDayOfYear(int day) { dayOfYear = day; } } C:UsersChristopherDocumentsNetBeansProjectsJRVampedsrcTestBirdSighting2.java import java.util.Scanner; public class TestBirdSighting2 { public static void main(String[] args)
  • 69. { System.out.println("DETAILS FOR FIRST BIRDS SIGHTING"); Scanner keyboard = new Scanner(System.in); System.out.print("Enter the bird species name;>> "); String species = keyboard.next(); System.out.print("How many of the species did you see?>> "); int numberSeen = keyboard.nextInt(); System.out.print("Enter the day of the year;>> "); int dayOfYear = keyboard.nextInt(); BirdSighting2 firstSight = new BirdSighting2(species, numberSeen, dayOfYear); System.out.println(""); System.out.println("On the First Sighting: "); System.out.println(numberSeen + " birds of the " + species + " species were seen on day " + dayOfYear + " of the year"); System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"); System.out.println("DETAILS FOR SECOND BIRDS SIGHTING"); Scanner keyEntry = new Scanner(System.in); System.out.print("Enter the bird species name;>> "); species = keyEntry.next(); System.out.print("How many of the species did you see?>> "); numberSeen = keyEntry.nextInt(); System.out.print("Enter the day of the year;>> "); dayOfYear = keyEntry.nextInt(); BirdSighting2 secondSight = new BirdSighting2(species, numberSeen, dayOfYear); System.out.println(""); System.out.println("On the Second Sighting: "); System.out.println(numberSeen + " birds of the " + species + " species were seen on day " + dayOfYear + " of the year"); System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"); System.out.println("DETAILS FOR THIRD BIRDS SIGHTING"); Scanner input = new Scanner(System.in); System.out.print("Enter the bird species name;>> "); species = input.next(); System.out.print("How many of the species did you see?>> "); numberSeen = input.nextInt(); System.out.print("Enter the day of the year;>> "); dayOfYear = input.nextInt(); BirdSighting2 thirdSight = new BirdSighting2(species, numberSeen, dayOfYear); System.out.println("");
  • 70. System.out.println("On the Third Sighting: "); System.out.println(numberSeen + " birds of the " + species + " species were seen on day " + dayOfYear + " of the year"); System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"); System.exit(0); } } 4. a. Create a class named BloodData that includes fields that hold a blood type (the four blood types are O, A, B, and AB) and an Rh factor (the factors are + and –). Create a default constructor that sets the fields to “O” and “+”, and an overloaded constructor that requires values for both fields. Include get and set methods for each field. Save this file as BloodData.java. Create an application named TestBloodData that demonstrates that each method works correctly. Save the application as TestBloodData.java. b. Create a class named Patient that includes an ID number, age, and BloodData. Provide a default constructor that sets the ID number to “0”, the age to 0, and the BloodData to “O” and “+”. Create an overloaded constructor that provides values for each field. Also provide get methods for each field. Save the file as Patient.java. Create an application named TestPatient that demonstrates that each method works correctly, and save it as TestPatient.java. //BloodData class C:UsersChristopherDocumentsNetBeansProjectsJRVampedsrcBloodData.java public class BloodData
  • 71. { // Create two private data fields private String bloodType; private String rhesusFactor; // Constructor with default values public BloodData() { bloodType = "O"; rhesusFactor = "+"; } // Constructor that receive values public BloodData(String type, String factor) { bloodType = type; rhesusFactor = factor; } // Get methods public String getBloodType() { return bloodType; } public String getRhesusFactor() { return rhesusFactor; } // Set methods public void setBloodType(String type) { bloodType = type; } public void setRhesusFactor(String factor) { rhesusFactor = factor; } } //TestBloodData main class C:UsersChristopherDocumentsNetBeansProjectsJRVampedsrcTestBloodData.java import java.util.Scanner; public class TestBloodData { public static void main(String[] args) { // Create default BloodData object that doesn't take parameters BloodData defaultType = new BloodData();
  • 72. String bloodType = defaultType.getBloodType(); String rhesusFactor = defaultType.getRhesusFactor(); // Default Blood Data Details System.out.println("BloodGroup is:>> " + bloodType + " ; Rhesus factor is:>> " + rhesusFactor + "n"); // Input data for the first BloodData object Scanner input = new Scanner(System.in); System.out.print("Enter first patient's Blood Group:>> "); bloodType = input.next(); System.out.print("Enter first patient's Rhesus Factor:>> "); rhesusFactor = input.next(); // Create the first BloodData object BloodData firstBloodData = new BloodData(bloodType, rhesusFactor); bloodType = firstBloodData.getBloodType(); rhesusFactor = firstBloodData.getRhesusFactor(); //Output of first patient's Blood Data System.out.println(""); System.out.println("Below is the first patient's blood data"); System.out.println("BloodGroup is:>> " + bloodType + " ; RhesusFactor is:>> " + rhesusFactor); System.out.println("~~~~~~~~~~~~~~~~~~~~ "); // Input data for the second BloodData object System.out.print("Enter second patient's Blood Group:>> "); bloodType = input.next(); System.out.print("Enter second patient's Rhesus Factor:>> "); rhesusFactor = input.next(); // Create the second BloodData object BloodData secondBloodData = new BloodData(bloodType, rhesusFactor); bloodType = secondBloodData.getBloodType(); rhesusFactor = secondBloodData.getRhesusFactor(); //Output of second patient's Blood Data System.out.println(""); System.out.println("Below is the second patient's blood data"); System.out.println("BloodGroup is:>> " + bloodType + " ; RhesusFactor is:>> " + rhesusFactor); System.out.println("~~~~~~~~~~~~~~~~~~~~ "); } }
  • 73. Part B C:UsersChristopherDocumentsNetBeansProjectsJRVampedsrcPatient.java public class Patient { // Create three private data fields, the third f // ield is an object of the BloodData class private int idNum; private int age; private BloodData bldData; // Constructor that returns default values public Patient() { bldData = new BloodData("O", "+"); idNum = 0; age = 0; } // Constructor that return user entered values public Patient(int idNo, int yAge, String bloodType, String rhesusFactor) { bldData = new BloodData(bloodType, rhesusFactor); age = yAge; idNum = idNo; } // get methods public String getBldGroup() { return bldData.getBloodType(); } public String getRhesusFactor() { return bldData.getRhesusFactor(); }
  • 74. public int getAge() { return age; } public int getIdNum() { return idNum; } // set methods public void setIdNum(int idNo) { idNum = idNo; } public void setAge(int yAge) { age = yAge; } } PARTB C:UsersChristopherDocumentsNetBeansProjectsJRVampedsrcTestPatient.java public class TestPatient { public static void main(String[] args) { Patient firstPatient = new Patient(); int idNum = firstPatient.getIdNum(); int age = firstPatient.getAge(); System.out.println("DEFAULT PATIENT BLOOD TYPE DETAILS"); System.out.println("Age:>>" + age ); System.out.println("ID#:>> " + idNum); System.out.println("Blood Group:>> " + firstPatient.getBldGroup()); System.out.println("Rhesus Factor:>> " + firstPatient.getRhesusFactor()); Patient secondPatient = new Patient(220909, 39, "O", "+"); System.out.println(""); System.out.println("FIRST PATIENT BLOOD TYPE DETAILS"); System.out.println("Age:>> " + secondPatient.getAge()); System.out.println("ID#:>> " + secondPatient.getIdNum()); System.out.println("Blood Group:>> " + secondPatient.getBldGroup()); System.out.println("Rhesus Factor:>> " + secondPatient.getRhesusFactor()); } }
  • 76. Page 236 6. a. Create a class named Circle with fields named radius, diameter, and area. Include a constructor that sets the radius to 1 and calculates the other two values. Also include methods named setRadius()and getRadius(). The setRadius() method not only sets the radius but also calculates the other two values. (The diameter of a circle is twice the radius, and the area of a circle is pi multiplied by the square of the radius. Use the Math class PI constant for this calculation.) Save the class as Circle.java. b. Create a class named TestCircle whose main() method declares several Circle objects. Using the setRadius() method, assign one Circle a small radius value, and assign another a larger radius value. Do not assign a value to the radius of the third circle; instead, retain the value assigned at construction. Display all the values for all the Circle objects. Save the application as TestCircle.java. Circle.java class C:UsersChristopherDocumentsNetBeansProjectsJRVampedsrcCircle.java public class Circle { // Declare data field variables associated with a circle private double radius; private double diameter; private double area; // Create a default constructor public Circle() { radius = 1.0; diameter = 2 * radius; area = Math.PI * radius * radius; } // Constructor that receive radius as a parameter public Circle(double rad) { radius = rad; diameter = 2 * rad; area = Math.PI * rad * rad; } //get methods public double getDiameter(double diam) { return diameter = 2 * radius; } public double getArea(double area) { return area = Math.PI * radius * radius;
  • 77. } public double getRadius() { return radius; } // Set method for setting radius of circle public void setRadius(double rad) { radius = rad; } } TestCircle.java class C:UsersChristopherDocumentsNetBeansProjectsJRVampedsrcTestCircle.java import java.util.Scanner; public class TestCircle { public static void main(String[] args) { // Creat a Scanner object for user input Scanner input = new Scanner(System.in); System.out.print("Enter the radius of the FIRST cicle:>> "); double radius = input.nextDouble(); // Instantiate first circle object Circle firstCircle = new Circle(radius); radius = firstCircle.getRadius(); double diameter = firstCircle.getDiameter(radius); double area = firstCircle.getArea(radius); System.out.println("Radius of firstCircle is:>> " + radius + " cm"); System.out.println("Diameter of firstCircle is:>> " + diameter + " cm"); System.out.println("Area of firstCircle is:>> " + area + " cm.sq"); System.out.println(" "); System.out.print("Enter the radius of the SECOND circle:>> "); double radius2 = input.nextDouble(); // instantiate second circle Circle secondCircle = new Circle(radius2); double diameter2 = secondCircle.getDiameter(radius2); double area2 = secondCircle.getArea(radius2); System.out.println("Radius of secondCircle is:>> " + radius2 + " cm"); System.out.println("Diameter of secondCircle is:>> " + diameter2 + " cm"); System.out.println("Area of firstCircle is:>> " + area2 + " cm.sq"); System.out.println(" "); Circle defaultCircle = new Circle(); // NOTE: THe radius and the diameter of the default circle are
  • 78. // those provided by the default constructor in Circle.java class // Users don't have to input values for these parameters double radiusD = defaultCircle.getRadius(); double diameterD = defaultCircle.getDiameter(radius); double areaD = defaultCircle.getArea(radius); System.out.println("DEFAULT VALUES ARE AUTO GENERATED"); System.out.println("AS PAR CONSTRUCTOR IN THE Circle.java class "); System.out.println( "Radius of defaultCircle is: = " + radiusD + " cm"); System.out.println( "Diameter of defaultCircle is: = " + diameterD + " cm"); System.out.println( "AREA of DEFAULT circle is: = " + areaD + " cm.sq"); System.out.println( " "); } }
  • 79. 5. a. Create a class for the Tip Top Bakery named Bread with data fields for bread type (such as “rye”) and calories per slice. Include a constructor that takes parameters for each field, and include get methods that return the values of the fields. Also include a public final static String named MOTTO and initialize it to The staff of life. Write an application named TestBread to instantiate three Bread objects with different values, and then display all the data, including the motto, for each object. Save both the Bread.java and TestBread.java files. //Bread class C:UsersChristopherDocumentsNetBeansProjectsJRVampedsrcBread.java public class Bread { //Two private data fields and one public data fields declared private String breadType; private int calories; public static final String MOTTO = "The staff of life."; //Constructor for Bread type public Bread(String type, int calori) { breadType = type; calories = calori; } // get methods public String getBreadType() { return breadType; } public int getCalories() { return calories; } // set methods public void setBreadType(String type) { breadType = type; } public void setCalories(int calori) { calories = calori; } } TestBread class C:UsersChristopherDocumentsNetBeansProjectsJRVampedsrcTestBread.java import java.util.Scanner; public class TestBread {
  • 80. public static void main(String[] args) { // Create a Scanner object for user inputs; Scanner input = new Scanner(System.in); // Enter the first bread type System.out.print("Enter the first bread type:>> "); String breadType = input.nextLine(); // Enter the number of calories for this bread type System.out.print("Enter first bread calories:>> "); int calories = input.nextInt(); System.out.println(" "); // Create a new Bread object Bread wBread; wBread = new Bread(breadType, calories); breadType = wBread.getBreadType(); calories = wBread.getCalories(); System.out.println(breadType + " bread has " + calories + " calories per loaf "); System.out.println(Bread.MOTTO); System.out.println(" ~~~~~~~~~ "); input.nextLine(); // to consume the line left from above // Enter the second bread type System.out.print("Enter the second bread type:>> "); String breadType2 = input.nextLine(); // Enter the number of calories for this bread type System.out.print("Enter second bread calories:>> "); int calories2 = input.nextInt(); System.out.println(" "); // Create a new Bread object Bread cBread; cBread = new Bread(breadType2, calories2); breadType2 = cBread.getBreadType(); calories2 = cBread.getCalories(); System.out.println(breadType2 + " bread has " + calories2 + " calories per loaf "); System.out.println(Bread.MOTTO); System.out.println(" ~~~~~~~~~ "); input.nextLine(); // to consume the line left from above // Enter the third bread type System.out.print("Enter the third bread type:>> "); String breadType3 = input.nextLine(); // Enter the number of calories for this bread type System.out.print("Enter third bread caloies:>> "); int calories3 = input.nextInt(); System.out.println(" ");
  • 81. // Create a new Bread object Bread oatBread; oatBread = new Bread(breadType3, calories3); breadType3 = oatBread.getBreadType(); calories3 = oatBread.getCalories(); System.out.println(breadType3 + " bread has " + calories3 + " calories per loaf "); System.out.println(Bread.MOTTO); System.out.println(" ~~~~~~~~~ "); } }
  • 82. 5 b. Create a class named SandwichFilling. Include a field for the filling type (such as “egg salad”) and another for the calories in a serving. Include a constructor that takes parameters for each field, and include get methods that return the values of the fields. Write an application named TestSandwichFilling to instantiate three SandwichFilling objects with different values, and then display all the data for each object. Save both the SandwichFilling.java and TestSandwichFilling.java files. //SandwichFilling class C:UsersChristopherDocumentsNetBeansProjectsJRVampedsrcSandwichFilling.java public class SandwichFilling { private String fillType; private int calories; // Constructor take values from parameters public SandwichFilling (String fill, int calori) { fillType = fill; calories = calori; } // get methods public String getFillType() { return fillType; } public int getCalories() { return calories; } public void setFillType(String fill) { fillType = fill; } public void setCalories(int calori) { calories = calori; } } //TestSandwichFilling.java C:UsersChristopherDocumentsNetBeansProjectsJRVampedsrcTestSandwichFilling.java import java.util.Scanner; // For user data input public class TestSandwichFilling {
  • 83. public static void main(String[] args) { // Create Scanner object for user inputs Scanner input = new Scanner(System.in); System.out.print("Enter First Sandwich filling:>> "); String fillType = input.nextLine(); System.out.print("Enter the calories per serving:>> "); int calories = input.nextInt(); System.out.println(" "); SandwichFilling firstFill = new SandwichFilling(fillType, calories); fillType = firstFill.getFillType(); calories = firstFill.getCalories(); System.out.println(fillType + " Sandwhich filling has " + calories + " calories per serving. "); System.out.print(" "); System.out.println("~~~~~~~~~~~"); System.out.print("Enter Second Sandwich filling:>> "); String fillType2 = input.next(); System.out.print("Enter the calories per serving:>> "); int calories2 = input.nextInt(); System.out.println(" "); SandwichFilling secondFill = new SandwichFilling(fillType2, calories2); fillType2 = secondFill.getFillType(); calories2 = secondFill.getCalories(); System.out.println(fillType2 + " Sandwhich filling has " + calories2 + " calories per serving. "); System.out.println("~~~~~~~~~~~"); System.out.print("Enter Third Sandwich filling:>> "); String fillType3 = input.next(); System.out.print("Enter the calories per serving:>> "); int calories3 = input.nextInt(); System.out.println(" "); SandwichFilling thirdFill = new SandwichFilling(fillType3, calories3); fillType3 = thirdFill.getFillType(); calories3 = thirdFill.getCalories(); System.out.println(fillType3 + " Sandwhich filling has " + calories3 + " calories per serving. "); System.out.println("~~~~~~~~~~~"); } }
  • 84. 5c. Create a class named Sandwich. Include a Bread field and a SandwichFilling field. Include a constructor that takes parameters for each field needed in the two objects and assigns them to each object’s constructor. Write an application named TestSandwich to instantiate three Sandwich objects with different values, and then display all the data for each object, including the total calories in a Sandwich, assuming that each Sandwich is made using two slices of Bread. Save both the Sandwich.java and TestSandwich.java files. //Sandwich.java C:UsersChristopherDocumentsNetBeansProjectsJRVampedsrcSandywich.java public class Sandywich { private Bread bread; private SandwichFilling fill; /** * The Sandywich class has four data fields, two from the Bread * class and two from the SandwichFilling class that were created * and used in previous questions */ public Sandywich(String breadType, int caloriesB, String fillType, int caloriesF) { // Create a new Bread object from the Bread class and a // new SandwichFilling object from SandwichFilling bread = new Bread(breadType, caloriesB); fill = new SandwichFilling(fillType, caloriesF); } /** It is not necessary to get methods for the individual data field separately * Instead, use is made of the get methods for the Bread and SandwichFilling * classes. Also, individual set methods are no longer needed because the public * methods in the Bread and SandwichFilling classes will be used to access their * respective private fields. */
  • 85. // get methods public String getBreadType() { return bread.getBreadType(); } public int getCaloriesB() { return bread.getCalories(); } public String getFillType() { return fill.getFillType(); } public int getCaloriesF() { return fill.getCalories(); } } //TestSandywich.java class C:UsersChristopherDocumentsNetBeansProjectsJRVampedsrcTestSandywich.java import java.util.Scanner; public class TestSandywich { public static void main(String[] args) { // Input the bread type and the calories per serving fo bread Scanner input = new Scanner(System.in); System.out.print("Enter the breadType:>> "); String breadType = input.next(); System.out.print("Enter the calories per bread serving:>> "); int caloriesB = input.nextInt(); System.out.print("Enter the sandwich filling:>> "); String fillType = input.next(); System.out.print("Enter the calories per sandwich serving:>> "); int caloriesF = input.nextInt(); // Create a new Sandywich object Sandywich tasteOne = new Sandywich(breadType, caloriesB, fillType, caloriesF); //Total calories per sandwichOne is calculated below int totalCalories = 2 * caloriesB + caloriesF; System.out.println(""); System.out.println("Bread type is: "+ tasteOne.getBreadType()); System.out.println("Calories per bread slice: " + tasteOne.getCaloriesB()); System.out.println("Sandwich filling type: " + tasteOne.getFillType());
  • 86. System.out.println("Calories per sandwich filling: " + tasteOne.getCaloriesF()); System.out.println("Calories per sandwichOne: = " + totalCalories); System.out.println(" ~~~~~~~~~~"); System.out.print("Enter the breadType:>> "); String breadType2 = input.next(); System.out.print("Enter the calories per bread slice:>> "); int caloriesB2 = input.nextInt(); System.out.print("Enter the sandwich filling:>> "); String fillType2 = input.next(); System.out.print("Enter the calories per sandwich filling;>> "); int caloriesF2 = input.nextInt(); Sandywich tasteTwo = new Sandywich(breadType2, caloriesB2, fillType2, caloriesF2); //Total calories per sandwichTwo is calculated below int totalCalories2 = 2 * caloriesB2 + caloriesF2; System.out.println(" "); System.out.println("Bread type is: "+ tasteTwo.getBreadType()); System.out.println("Calories per bread slice: " + tasteTwo.getCaloriesB()); System.out.println("Sandwich filling type: " + tasteTwo.getFillType()); System.out.println("Calories per sandwich filling: " + tasteTwo.getCaloriesF()); System.out.println("Calories per sandwichTwo: = " + totalCalories2); System.out.println(" ~~~~~~~~~~"); System.out.print("Enter the breadType:>> "); String breadType3 = input.next(); System.out.print("Enter the calories per bread serving:>> "); int caloriesB3 = input.nextInt(); System.out.print("Enter the sandwich filling:>> "); String fillType3 = input.next(); System.out.print("Enter the calories per sandwich filling;>> "); int caloriesF3= input.nextInt(); Sandywich tasteThree = new Sandywich(breadType3, caloriesB3, fillType3, caloriesF3); //Total calories per sandwichThree is calculated below int totalCalories3 = 2 * caloriesB3 + caloriesF3; System.out.println(""); System.out.println("Bread type is: "+ tasteThree.getBreadType()); System.out.println("Calories per bread slice: " + tasteThree.getCaloriesB()); System.out.println("Sandwich filling type: " + tasteThree.getFillType()); System.out.println("Calories per sandwich filling: " + tasteThree.getCaloriesF()); System.out.println("Calories per sandwichThree: = " + totalCalories3); System.out.println(" ~~~~~~~~~~"); } }
  • 87. 7. Write a Java application that uses the Math class to determine the answers for each of the following: a. The square root of 37 b. The sine and cosine of 300
  • 88. c. The value of the floor, ceiling, and round of 22.8 d. The larger and the smaller of the character “D” and the integer 71 e. A random number between 0 and 20 (Hint: The random() method returns a value between 0 and 1; you want a number that is 20 times larger.) Save the application as MathTest.java. package MyJavaLab; public class TestMath { public static void main(String[] args) { double x = 37; double y = 300; double z = 22.8; int number = (int)(20 * Math.random()); System.out.println("Square root of 37 is: " + Math.sqrt (x)); System.out.println(""); System.out.println("Sine of 300 is: " + Math.sin(y)); System.out.println(""); System.out.println("Cosine of 300 is: " + Math.cos(y)); System.out.println(""); System.out.println("floor(22.8) is the largest integral value not greater than 22.8: " + Math.floor(z)); System.out.println(""); System.out.println("ceil(22.8) is the smallest integral value not less than 22.8: " + Math.floor(z)); System.out.println(""); System.out.println("round(22.8) is the closest integer value to 22.8: " + Math.floor(z)); System.out.println(""); System.out.println("Random number is: " + number); } }
  • 89. Worked Example page 200 Creating Overloaded Constructors In this section, you create a class with overloaded constructors and demonstrate how they work. 1. Open a new file in your text editor, and start the CarInsurancePolicy class as follows. The class contains three fields that hold a policy number, the number of payments the policy holder will make annually, and the policy holder’s city of residence. public class CarInsurancePolicy { private int policyNumber; private int numPayments; private String residentCity; 2. Create a constructor that requires parameters for all three data fields. public CarInsurancePolicy(int num, int payments, String city) { policyNumber = num; numPayments = payments; residentCity = city; } 3. Suppose the agency that sells car insurance policies is in the city of Mayfield. Create a two-parameter constructor that requires only a policy number and number of payments. This constructor assigns Mayfield to residentCity. public CarInsurancePolicy(int num, int payments) { policyNumber = num; numPayments = payments; residentCity = "Mayfield"; } 4. Add a third constructor that requires only a policy number parameter. This constructor uses the default values of two annual payments and Mayfield as the resident city. (Later in this chapter, you will learn how to eliminate the duplicated assignments in these constructors.) public CarInsurancePolicy(int num) { policyNumber = num; numPayments = 2; residentCity = "Mayfield";
  • 90. 5. Add a display() method that outputs all the insurance policy data: public void display() { System.out.println("Policy #" + policyNumber + ". " + numPayments + " payments annually. Driver resides in " + residentCity + "."); } 6. Add a closing curly brace for the class. Save the file as CarInsurancePolicy.java. 7. Open a new text file to create a short application that demonstrates the constructors at work. The application declares three CarInsurancePolicy objects using a different constructor version each time. Type the following code: public class CreatePolicies { public static void main(String[] args) { CarInsurancePolicy first = new CarInsurancePolicy(123); CarInsurancePolicy second = new CarInsurancePolicy(456, 4); CarInsurancePolicy third = new CarInsurancePolicy (789, 12, "Newcastle"); 8. Display each object, and add closing curly braces for the method and the class: first.display(); second.display(); third.display(); } } 9. Save the file as CreatePolicies.java, and then compile and test the program. The output appears in Figure 4-23. }
  • 91. 10. Add a fourth declaration to the CreatePolicies class that attempts to create a CarInsurancePolicy object using a default constructor: CarInsurancePolicy fourth = new CarInsurancePolicy(); 11. Save and compile the revised CreatePolicies program. The class does not compile because the CarInsurancePolicy class does not contain a default constructor. Change the newly added declaration to a comment, compile the class again, and observe that the class now compiles correctly.
  • 92. Using the this Reference to Make Constructors More Efficient In this section, you modify the CarInsurancePolicy class so that its constructors are more efficient. 1. Open the CarInsurancePolicy.java file. Change the class name to CarInsurancePolicy2, and immediately save the file as CarInsurancePolicy2.java. 2. Change the name of the three-parameter constructor from CarInsurancePolicy() to CarInsurancePolicy2(). 3. Replace the constructor that accepts a single parameter for the policy number with the following constructor. The name of the constructor is changed from the earlier version, and this one passes the policy number and two constant values to the three-parameter constructor: public CarInsurancePolicy2(int num) { this(num, 2, "Mayfield"); } 4. Replace the constructor that accepts two parameters (for the policy number and number of payments) with the following constructor. This constructor has a new name and passes the two parameters and one constant value to the three-parameter constructor: public CarInsurancePolicy2(int num, int payments) { this(num, payments, "Mayfield"); } 5. Save the file, and compile it. 6. Open the CreatePolicies.java file that demonstrates the use of the different constructor versions. Change the class name to CreatePolicies2, and save the file as CreatePolicies2.java. 7. Add the digit 2 in six places—three times to change the class name CarInsurancePolicy to CarInsurancePolicy2 when the name is used as a data type, and in the three constructor calls. 8. Save the file, and then compile and execute it. The output is identical to that shown in Figure 4-23 in the previous “You Do It” section, but the repetitious constructor code has been eliminated. 9. You can further reduce the code in the CarInsurancePolicy class by changing the single-parameter constructor to the following, which removes the constant "Mayfield" from the constructor call:
  • 93. public CarInsurancePolicy2(int num) { this(num, 2); } Now, the single-parameter version calls the two-parameter version and passes the policy number and the constant 2. In turn, the two-parameter version calls the three-parameter version, adding "Mayfield" as the city. 10. Save this version of the CarInsurancePolicy2 class, and compile it. Then recompile the CreatePolicies2.java file, and execute it. The output remains the same.
  • 94. Using Static and Nonstatic final Fields (Worked Example on page 213) In this section, you create a class for the Riverdale Kennel Club to demonstrate the use of static and nonstatic final fields. The club enters its dogs in an annual triathlon event in which each dog receives three scores in agility, conformation, and obedience. 1. Open a new file in your text editor, and enter the first few lines for a DogTriathlonParticipant class. The class contains a final field that holds the number of events in which the dog participated. Once a final field is set, it never should change. The field is not static because it is different for each dog. The class also contains a static field that holds the total cumulative score for all the participating dogs. The field is not final because its value increases as each dog participates in the triathlon, but it is static because at any moment in time, it is the same for all participants. public class DogTriathlonParticipant { private final int NUM_EVENTS; private static int totalCumulativeScore = 0; 2. Add six private fields that hold the participating dog’s name, the dog’s score in three events, the total score, and the average score: private String name; private int obedienceScore; private int conformationScore; private int agilityScore; private int total; private double avg; 3. The constructor for the class requires five parameters—the dog’s name, the number of events in which the dog participated, and the dog’s scores in the three events. (After you read the chapter on decision making, you will be able to ensure that the number of nonzero scores entered matches the number of events, but for now no such checks will be made.) The constructor assigns each value to the appropriate field. public DogTriathlonParticipant(String name, int numEvents, int score1, int score2, int score3) { this.name = name; NUM_EVENTS = numEvents; obedienceScore = score1; conformationScore = score2; agilityScore = score3;
  • 95. 4. After the assignments, the constructor calculates the total score for the participant and the participant’s average score. Notice the result of the division is cast to a double so that any fractional part of the calculated average is not lost. Also, add the participant’s total score to the cumulative score for all participants. Recall that this field is static because it should be the same for all participants at any point in time. After these statements, add a closing curly brace for the constructor. total = obedienceScore + conformationScore + agilityScore; avg = (double) total / NUM_EVENTS; totalCumulativeScore = totalCumulativeScore + total; } 5. Start a method that displays the data for each triathlon participant. public void display() { System.out.println(name + " participated in " + NUM_EVENTS + " events and has an average score of " + avg); System.out.println(" " + name + " has a total score of " + total + " bringing the total cumulative score to " + totalCumulativeScore); } 6. Add a closing curly brace for the class. Then, save the file as DogTriathlonParticipant.java. Compile the class, and correct any errors. 7. Open a new file in your text editor, and then enter the header and opening and closing curly braces for a class you can use to test the DogTriathlonParticipant class. Also include a main() method header and its opening and closing braces. public class TestDogs { public static void main(String[] args) { } } 8. Between the braces of the main() method, declare a DogTriathlonParticipant object. Provide values for the participant’s name, number of events, and three scores, and then display the object. DogTriathlonParticipant dog1 = new DogTriathlonParticipant("Bowser", 2, 85, 89, 0); dog1.display();
  • 96. 9. Create and display two more objects within the main() method. DogTriathlonParticipant dog2 = new DogTriathlonParticipant("Rush", 3, 78, 72, 80); dog2.display(); DogTriathlonParticipant dog3 = new DogTriathlonParticipant("Ginger", 3, 90, 86, 72); dog3.display(); 10. Save the file as TestDogs.java. Compile and execute the program. The output looks like Figure 4-36. Visually confirm that each total, average, and cumulative total is correct. 11. Experiment with the DogTriathlonParticipant class and its test class. For example, try the following:  Add a new statement at the end of the TestDogs class that again displays the data for any one of the participants. Note that as long as no new objects are created, the cumulative score for all participants remains the same no matter which participant uses it.  Try to assign a value to the NUM_EVENTS constant from the display() method, and then compile the class and read the error message generated.  Remove the keyword static from the definition of totalCumulativeScore in the DogTriathlonParticipant class, and then recompile the classes and run the program. Notice in the output that the nonstatic cumulative score no longer reflects the cumulative score for all objects but only the score for the current object using the display() method.  Use 0 as the number of events for an object. When the participant’s average is calculated, the result is not numeric, and NaN is displayed. NaN is an acronym for Not a Number. In the next chapter, you will learn to make decisions, and then you can prevent the NaN output.
  • 97. Example on Page 220 As an example of how to use a GregorianCalendar object, Figure 4-37 shows an AgeCalculator application. In this class, a default GregorianCalendar object named now is created. The user is prompted for a birth year, the current year is extracted from the now object using the get() method, and the user’s age this year is calculated by subtracting the birth year from the current year. Figure 4-38 shows the output when a user born in 1986 runs the application in 2014.
  • 98. Demonatrating the use of GregorianCalendar method – page 222 import java.util.*; public class CalendarDemo { public static void main(String[] args) { GregorianCalendar now = new GregorianCalendar(); System.out.println("YEAR: " + now.get(Calendar.YEAR) ); System.out.println("MONTH: " + now.get(Calendar.MONTH)); System.out.println("WEEK_OF_YEAR: " + now.get(Calendar.WEEK_OF_YEAR)); System.out.println("DATE: " + now.get(Calendar.DATE)); System.out.println("WEEK_OF_MONTH: " + now.get(Calendar.WEEK_OF_MONTH)); System.out.println("DAY_OF_MONTH: " + now.get(Calendar.DAY_OF_MONTH)); System.out.println("DAY_OF_YEAR: " + now.get(Calendar.DAY_OF_YEAR)); System.out.println("DAY_OF_WEEK: " + now.get(Calendar.DAY_OF_WEEK)); System.out.println("AM_PM: " + now.get(Calendar.AM_PM)); System.out.println("HOUR: " + now.get(Calendar.HOUR)); System.out.println("HOUR_OF_DAY: " + now.get(Calendar.HOUR_OF_DAY)); System.out.println("MINUTE: " + now.get(Calendar.MINUTE)); System.out.println("SECOND: " + now.get(Calendar.SECOND)); System.out.println("MILLISECOND: " + now.get(Calendar.MILLISECOND)); } }
  • 99. Worked example on page 249 import java.util.Scanner; public class AssignVounteer { public static void main(String[] args) { int donationType; String volunteer; final int CLOTHING_CODE = 1; final int OTHER_CODE = 2; final String CLOTHING_PRICER = "Regina"; final String OTHER_PRICER = "Marco"; Scanner input = new Scanner(System.in); System.out.println("What type of donation is this?"); System.out.print("Enter " + CLOTHING_CODE + " Clothing, " + OTHER_CODE + " for anything else... "); donationType = input.nextInt(); if(donationType == CLOTHING_CODE) volunteer = CLOTHING_PRICER; else volunteer = OTHER_PRICER; System.out.println("You entered " + donationType); System.out.println("The volunteer who will price this item is " + volunteer); } } Below is the output when the above code was ran with a selection of 1 On running the code with selection of 2
  • 100. Example page 254 import java.util.Scanner; public class AssignVounteer2 { public static void main(String[] args) { int donationType; String volunteer; final int CLOTHING_CODE = 1; final int OTHER_CODE = 2; final String CLOTHING_PRICER = "Regina"; final String OTHER_PRICER = "Marco"; String message; Scanner input = new Scanner(System.in); System.out.println("What type of donation is this?"); System.out.print("Enter " + CLOTHING_CODE + " Clothing, " + OTHER_CODE + " for anything else... "); donationType = input.nextInt(); if(donationType == CLOTHING_CODE) { volunteer = CLOTHING_PRICER; message = "clothing donation"; } else { volunteer = OTHER_PRICER; message = "another donation type"; } System.out.println("This is " + message); System.out.println("The volunteer who will price this item is " + volunteer); } } The outputs obtained from running the above code with selection 1 and then 2 are shown below:
  • 101. Example on page 259. The code above is modified to display the output below when any code other than 1 or 2 are entered into the selection. import java.util.Scanner; public class AssignVounteer3 { public static void main(String[] args) { int donationType; String volunteer; final int CLOTHING_CODE = 1; final int OTHER_CODE = 2; final String CLOTHING_PRICER = "Regina"; final String OTHER_PRICER = "Marco"; String message; Scanner input = new Scanner(System.in); System.out.println("What type of donation is this?"); System.out.print("Enter " + CLOTHING_CODE + " Clothing, " + OTHER_CODE + " for anything else >>> "); donationType = input.nextInt(); if(donationType == CLOTHING_CODE) { volunteer = CLOTHING_PRICER; message = "clothing donation"; } else { volunteer = OTHER_PRICER; message = "another donation type"; } if(donationType != CLOTHING_CODE) if(donationType != OTHER_CODE) { volunteer = "INVALID."; message = "an invalid donation type."; } System.out.println("This is " + message); System.out.println("The volunteer who will price this item is " + volunteer); } }
  • 102. Example on page 253 import java.util.Scanner; public class Payroll { public static void main(String[] args) { double rate; double hoursWorked; double regularPay; double overtimePay; final int FULL_WEEK = 40; final double OT_RATE = 1.5; Scanner keyboard = new Scanner(System.in); System.out.print("How many hours did you work this week? "); hoursWorked = keyboard.nextDouble(); System.out.print("What is your regular pay rate? "); rate = keyboard.nextDouble(); if(hoursWorked > FULL_WEEK) { regularPay = FULL_WEEK * rate; overtimePay = (hoursWorked - FULL_WEEK) * OT_RATE * rate; } else { regularPay = hoursWorked * rate; overtimePay = 0.0; } System.out.println("Regular pay is " + regularPay + "nOvertime pay is " + overtimePay); } }
  • 104. Example on Page 274 import java.util.Scanner; public class Assignment4 { public static void main(String[] args) { int donationType; String volunteer; final int CLOTHING_CODE = 1; final int FURNITURE_CODE = 2; final int ELECTRONICS_CODE = 3; final int OTHER_CODE = 4; final String CLOTHING_PRICER = "Regina"; final String OTHER_PRICER = "Marco"; final String FURNITURE_PRICER = "Walter"; final String ELECTRONICS_PRICER = "lydia"; String message; Scanner input = new Scanner(System.in); System.out.print("Enter an integer ..."); System.out.print("Enter " + CLOTHING_CODE + " Clothing, " + OTHER_CODE + " for anything else >>> "); donationType = input.nextInt(); switch (donationType) { case (CLOTHING_CODE): volunteer = CLOTHING_PRICER; message = "a clothing donation"; break; case (FURNITURE_CODE): volunteer = FURNITURE_PRICER; message = "a furniture donation"; break; case (ELECTRONICS_CODE): volunteer = ELECTRONICS_PRICER; message = "an electronics donation"; break; case (OTHER_CODE): volunteer = OTHER_PRICER; message = "another donation type"; break; default: volunteer = "invalid"; message = "an invalid donation type"; } System.out.println("You entered " + donationType); System.out.println("This is " + message); System.out.println("The volunteer who will price this item is " + volunteer);
  • 105. } }
  • 106. Page 291 Q1 1. Write an application that asks a user to enter an integer. Display a statement that indicates whether the integer is even or odd. Save the file as EvenOdd.java. C:UsersChristopherDocumentsNetBeansProjectsJDMay2018srcEvenOdd.java import java.util.Scanner; public class EvenOdd { public static void main(String[] args) { int num; Scanner keyboard = new Scanner(System.in); System.out.print("Enter any number greater than 0:>> "); num = keyboard.nextInt(); int number = num % 2; if(number == 0) { System.out.println("This is an EVEN number"); } else System.out.println("This is an ODD number"); System.exit(0); } }
  • 107. Page 291 Q2. 2. Write an application that prompts the user for the day’s high and low temperatures. If the high is greater than or equal to 90 degrees, display the message, “Heat warning.” If the low is less than 32 degrees, display the message “Freeze warning.” If the difference between the high and low temperatures is more than 40 degrees, display the message, “Large temperature swing.” Save the file as Temperatures.java. C:UsersChristopherDocumentsNetBeansProjectsJRVampedsrcTemperatures.java import java.util.Scanner; public class Temperatures { public static void main(String[] args) { double highTemp; double lowTemp; Scanner keyboard = new Scanner(System.in); System.out.print("Enter the day's high temperature. >>> "); highTemp = keyboard.nextDouble(); System.out.print("Enter today's low temperature. >> "); lowTemp = keyboard.nextDouble(); if (highTemp >= 90) { System.out.println("Heat warning"); } else if (lowTemp <= 32) { System.out.println("Freeze warning"); } if (highTemp - lowTemp > 40) System.out.println("Large temperature swing"); } }
  • 108. 3. a. Page 291 Write an application for the Summerdale Condo Sales office; the program determines the price of a condominium. Ask the user to choose 1 for park view, 2 for golf course view, or 3 for lake view. The output is the name of the chosen view as well as the price of the condo. Park view condos are $150,000, condos with golf course views are $170,000, and condos with lake views are $210,000. If the user enters an invalid code, set the price to 0. Save the file as CondoSales.java. C:UsersChristopherDocumentsNetBeansProjectsJRVampedsrcCondoSales.java import java.util.Scanner; public class CondoSales { public static void main(String[] args) { int condoCode; final double PARK_VIEW_COST = 150000; final double GOLF_COURSE_VIEW_COST = 170000; final double LAKE_VIEW_COST = 210000; Scanner keyboard = new Scanner(System.in); System.out.println("Enter the condo code: 1 for Park view; " + "2 for Golf course view; 3 for Lake view. >>>"); condoCode = keyboard.nextInt(); switch (condoCode) { case 1: System.out.println("Park view condo costs: $" + PARK_VIEW_COST ); break; case 2: System.out.println("Golf Course view condo costs: $" + GOLF_COURSE_VIEW_COST); break; case 3: System.out.println("Lake view condo costs: $" + LAKE_VIEW_COST); break; default: System.out.print("Invalid code selected. "); break; } } }
  • 109. Page 291 3b. Add a prompt to the CondoSales application to ask the user to specify a (1) garage or a (2) parking space, but only if the condo view selection is valid. Add $5,000 to the price of any condo with a garage. If the parking value is invalid, display an appropriate message and assume that the price is for a condo with no garage. Save the file as CondoSales2.java. C:UsersChristopherDocumentsNetBeansProjectsJRVampedsrcCondoSales2.java import java.util.Scanner; public class CondoSales2 { public static void main(String[] args) { int condoCode; int spaceCode; final double PARK_VIEW_COST = 150000; final double GOLF_COURSE_VIEW_COST = 170000; final double LAKE_VIEW_COST = 210000; final double GARAGE_COST = 5000; Scanner keyboard = new Scanner(System.in); System.out.println("Enter the condo code: 1 for Park view; " + " 2 for Golf course view; 3 for Lake View. >>>"); condoCode = keyboard.nextInt(); System.out.println("Enter the parking space code: 1 for Garage; " + "2 for Parking Space; >>>"); spaceCode = keyboard.nextInt(); if (((condoCode==1)||(condoCode==2)||(condoCode==3)) && !(condoCode > 3) &&(spaceCode ==1)) { switch (condoCode) { case 1: System.out.println("Park view condo with garage costs: $" + PARK_VIEW_COST + " + $" + GARAGE_COST + " for garage space" ); break; case 2: System.out.println("Golf Course view condo with garage costs: $" + GOLF_COURSE_VIEW_COST + " + $" + GARAGE_COST + " for garage"); break; case 3: System.out.println("Lake view condo with garage costs $" + LAKE_VIEW_COST + " + $" + GARAGE_COST + " for garage."); break; default: System.out.print("Invalid code selected. "); break; } } else if (spaceCode < 3)
  • 110. { switch (condoCode) { case 1: System.out.println("Park view condo costs: $" + PARK_VIEW_COST ); break; case 2: System.out.println("Golf Course view condo costs: $" + GOLF_COURSE_VIEW_COST); break; case 3: System.out.println("Lake view condo costs: $" + LAKE_VIEW_COST); break; default: System.out.print("INVALID Condo Code selected. "); break; } } else System.out.println("INVALID Space Code selected"); } }
  • 111. 4. a. The Williamsburg Women’s Club offers scholarships to local high school students who meet any of several criteria. Write an application that prompts the user for a student’s numeric high school grade point average (for example, 3.2), the student’s number of extracurricular activities, and the student’s number of service activities. Display the message “Scholarship candidate” if the student has any of the following:  A grade point average of 3.8 or above and at least one extracurricular activity and one service activity  A grade point average below 3.8 but at least 3.4 and a total of at least three extracurricular and service activities  A grade point average below 3.4 but at least 3.0 and at least two extracurricular activities and three service activities If the student does not meet any of the qualification criteria, display “Not a candidate.” Save the file as Scholarship.java. C:UsersChristopherDocumentsNetBeansProjectsJRVampedsrcScholarship.java import java.util.Scanner; public class Scholarship { public static void main(String[] args) { //declare string variable for holding message String message; //declare student's gpa as double double gpa; int extraCurr = 0; int service = 0; Scanner keyboard = new Scanner(System.in); System.out.print("Enter student's gpa. >> "); gpa = keyboard.nextDouble(); System.out.print("Number of extra curricular activities: >> "); extraCurr = keyboard.nextInt(); System.out.print("Number of other services: >> "); service = keyboard.nextInt(); int activitySum = extraCurr + service; // The logic below satisfies the first condition for scholarship // (gpa >= 3.8)&&(extraCurr >= 1)&&(service >= 1) // The logic below satisfies the second condition for scholarship // (((!(gpa < 3.4))||(gpa < 3.8))&&(!(activitySum < 3))) // The logic below satisfies the third condition for scholarship // ((gpa >= 3)||(gpa < 3.4))&&(extraCurr >=2)&& (service >= 3) // All the three conditions above are combined in the if statement // below if the statement below executes to true => Scholarship
  • 112. // if the statement executes to false => No Scholarship if (((gpa >= 3.8)&&(extraCurr >= 1)&&(service >= 1))||(((!(gpa < 3.4))|| (gpa < 3.8))&&(!(activitySum < 3)))||(((((gpa >= 3)||(gpa < 3.4))&& (extraCurr >=2))&& (service >= 3)))) message = "Scholarship Candidate. "; else message = "NOT a Scholarship candidate. "; System.out.println(message); System.exit(0); } }
  • 113. 4 b. Modify the Scholarship application so that if a user enters a grade point average under 0 or over 4.0, or a negative value for either of the activities, an error message appears. Save the file as Scholarship2.java C:UsersChristopherDocumentsNetBeansProjectsJRVampedsrcScholarship2.java import java.util.Scanner; public class Scholarship2 { public static void main(String[] args) { //declare string variable for holding message String message; //declare student's gpa as double double gpa; int extraCurr = 0; int service = 0; Scanner keyboard = new Scanner(System.in); System.out.print("Enter student's gpa. >> "); gpa = keyboard.nextDouble(); System.out.print("Number of extra curricular activities: >> "); extraCurr = keyboard.nextInt(); System.out.print("Number of other services: >> "); service = keyboard.nextInt(); int activitySum = extraCurr + service; // The logic below satisfies the first condition for scholarship // (gpa >= 3.8) && (extraCurr >= 1) && (service >= 1) // The logic below satisfies the second condition for scholarship // (((!(gpa < 3.4)) || (gpa < 3.8)) && (!(activitySum < 3))) // The logic below satisfies the third condition for scholarship // ((gpa >= 3) || (gpa < 3.4)) && (extraCurr >=2) && (service >= 3) // All the three conditions above are combined in the if statement below // if the statement below executes to true => Scholarship // if the statement executes to false => No Scholarship if (((gpa >= 3.8) && (extraCurr >= 1) && (service >= 1)) || (((!(gpa < 3.4)) || (gpa < 3.8)) && (!(activitySum < 3))) || (((((gpa >= 3) || (gpa < 3.4)) && (extraCurr >=2)) && (service >= 3)))) message = "Scholarship Candidate. "; else message = "NOT a Scholarship candidate. "; //The next line checks if invalid parameters were entered. if((gpa<0) || (gpa>4) || (service < 0) || (extraCurr < 0)) message = "Error!: Invalid values"; System.out.println(message);
  • 115. Q5 page 292 (CODE NOT COMPLETED) User should be able to make selection indefinitely till he wants to stop. But this application stops working properly after second selection made by the user) 5. Write an application that displays a menu of three items for the Jivin’ Java Coffee Shop as follows: Prompt the user to choose an item using the number (1, 2, or 3) that corresponds to the item, or to enter 0 to quit the application. After the user makes the first selection, if the choice is 0, display a total bill of $0. Otherwise, display the menu again. The user should respond to this prompt with another item number to order or 0 to quit. If the user types 0, display the cost of the single requested item. If the user types 1, 2, or 3, add the cost of the second item to the first, and then display the menu a third time. If the user types 0 to quit, display the total cost of the two items; otherwise, display the total for all three selections. Save the file as Coffee.java. Iteration 2 C:UsersChristopherDocumentsNetBeansProjectsJRVampedsrcCoffee.java import java.util.Scanner; public class Coffee { public static void main(String[] args) { int numSelected; //option selected 1, 2, 3 or 0 double orderCost = 0.0; //total value for ordered items double americanCost = 1.99; //per unit cost American double espressoCost = 2.50; //per unit cost espresso double latteCost = 2.15; ////per unit cost latte //the next lines instructs user to make selection Scanner keyboard = new Scanner(System.in); System.out.print("Enter your order; 1 = American; 2 = Espresso; 3 = Latte; 0 = Quit >> "); numSelected = keyboard.nextInt(); if (numSelected == 0) //if user select 0, Total bill is displayed as $0.0 below { System.out.print("Add another item: 1 = American; 2 = Espresso; " + "3 = Latte; 0 = Quit >> ");
  • 116. numSelected = keyboard.nextInt(); if(numSelected == 0) System.out.print("Quit)"); System.exit(0); } else if (numSelected > 0) { switch(numSelected) { case 1: orderCost = orderCost + americanCost; break; case 2: orderCost = orderCost + espressoCost; break; case 3: orderCost = orderCost + latteCost; break; default: System.out.print("Invalid entry "); System.out.println("Order Cost = " + orderCost); } System.out.print("Add another item: 1 = American; 2 = Espresso; " + "3 = Latte; 0 = Quit >> "); numSelected = keyboard.nextInt(); if(numSelected == 0) { System.out.print("Quit)"); System.exit(0); } else if(numSelected >= 0) { switch(numSelected) { case 1: orderCost = orderCost + americanCost; break; case 2: orderCost = orderCost + espressoCost; break; case 3: orderCost = orderCost + latteCost; break; default: System.out.print("Invalid entry "); } System.out.println("Order Cost = " + orderCost); System.out.print("Add another item: 1 = American; 2 = Espresso; " + "3 = Latte; 0 = Quit >> ");
  • 117. numSelected = keyboard.nextInt(); if(numSelected == 0) { System.out.print("Quit)"); System.exit(0); } else if(numSelected >= 0) { switch(numSelected) { case 1: orderCost = orderCost + americanCost; break; case 2: orderCost = orderCost + espressoCost; break; case 3: orderCost = orderCost + latteCost; break; default: System.out.print("Invalid entry "); } System.out.println("Order Cost = " + orderCost); System.out.print("Add another item: 1 = American; 2 = Espresso; " + "3 = Latte; 0 = Quit >> "); numSelected = keyboard.nextInt(); if(numSelected == 0) System.out.println("Order Cost = " + orderCost); } } } } } /*for non 0 selection, user is presented with the option of making additional selections or quit. The app then display the cost for first selection or adds the cost of first selection to the cost of second selection and display the total bill for the order placed. */ SOLUTION (Iteration 1) import java.util.Scanner; public class Coffee { public static void main(String[] args) { int numSelected; //option selected 1, 2, 3 or 0 double orderCost = 0.0; //total value for ordered items double americanCost = 1.99; //per unit cost American double espressoCost = 2.50; //per unit cost espresso double latteCost = 2.15; ////per unit cost latte //the next lines instructs user to make selection Scanner keyboard = new Scanner(System.in);
  • 118. System.out.print("Enter your order; 1 = American; 2 = Espresso; 3 = Latte; 0 = Quit >> "); numSelected = keyboard.nextInt(); if (numSelected == 0) //if user select 0, Total bill is displayed as $0.0 below System.out.println("Total Bill = $0.00"); /*for non 0 selection, user is presented with the option of making additional selections or quit. The app then display the cost for first selection or adds the cost of first selection to the cost of second selection and display the total bill for the order placed. */ else System.out.print("Add another item: 1 = American; 2 = Espresso; 3 = Latte; 0 = Quit >> "); numSelected = keyboard.nextInt(); if (numSelected ==1) { if(numSelected == 0) orderCost = americanCost; if (numSelected == 1) orderCost = 2 * americanCost; if (numSelected == 2) orderCost = americanCost + espressoCost; if (numSelected == 3) orderCost = americanCost + latteCost; } if (numSelected ==2) { if(numSelected == 0) orderCost = espressoCost; if (numSelected == 1) orderCost = espressoCost + americanCost; if (numSelected == 2) orderCost = 2 * espressoCost; //System.out.print("Total Bill is = $" + orderCost); if (numSelected == 3) orderCost = espressoCost + latteCost; } if (numSelected ==3) { if(numSelected == 0) orderCost = latteCost; if (numSelected == 1) orderCost = latteCost + americanCost; if (numSelected == 2) orderCost = latteCost + espressoCost; if (numSelected == 3) orderCost = 2 * latteCost; } System.out.println("Add another item: Enter 1 for American, 2 for Espresso, 3 for Latte, Enter 0 to Quit >> "); numSelected = keyboard.nextInt(); if (numSelected ==0)
  • 119. System.out.println("Total Bill = $" + orderCost); } }
  • 120. Q6 page 292 Barnhill Fastener Company runs a small factory. The company employs workers who are paid one of three hourly rates depending on skill level: Each factory worker might work any number of hours per week; any hours over 40 are paid at one and one-half times the usual rate. In addition, workers in skill levels 2 and 3 can elect the following insurance options: Also, workers in skill level 3 can elect to participate in the retirement plan at 3% of their gross pay. Write an interactive Java payroll application that calculates the net pay for a factory worker. The program prompts the user for skill level and hours worked, as well as appropriate insurance and retirement options for the employee’s skill level category. The application displays: (1) the hours worked, (2) the hourly pay rate, (3) the regular pay for 40 hours, (4) the overtime pay, (5) the total of regular and overtime pay, and (6) the total itemized deductions. If the deductions exceed the gross pay, display an error message; otherwise, calculate and display (7) the net pay after all the deductions have been subtracted from the gross. Save the file as Pay.java. C:UsersChristopherDocumentsNetBeansProjectsJRVampedsrcPay.java import java.util.Scanner; public class Pay { public static void main(String[] args) { // Declare variables int skillLevel; int hoursWorked; int insuranceOption; int retirementOption; double hourlyPayRate = 0.0; final double LOW_PAY_RATE = 17.00; final double MEDIUM_PAY_RATE = 20.00; final double HIGH_PAY_RATE = 22.00;
  • 121. //Insurance deduction for applicable workers double insuranceRate; double regularPay = 0; double overTimePay = 0; double totalPay = regularPay + overTimePay; double insuranceCost = 0; final double RETIREMENT_RATE = 0.03; double retirementDeductions = 0; // Declared & initialized to 0 double totalDeductions = 0; // Declared & initialized to 0 double netPay = totalPay - insuranceCost; Scanner keyboard = new Scanner(System.in); System.out.print("Enter skill level; 1, 2 or 3: >> "); skillLevel = keyboard.nextInt(); System.out.print("Enter hours worked. >> "); hoursWorked = keyboard.nextInt(); System.out.print("Enter insurance option. >> "); insuranceOption = keyboard.nextInt(); System.out.print("Enter retirement option. >> "); retirementOption = keyboard.nextInt(); // Calculating the net pay for Skill Level 1 // with hours worked <= 40. if((skillLevel == 1) && (hoursWorked <= 40)) { hourlyPayRate = LOW_PAY_RATE; regularPay = hoursWorked * hourlyPayRate; overTimePay = 0.0; totalPay = regularPay + overTimePay; insuranceCost = 0.00; retirementDeductions = 0.00; totalDeductions = insuranceCost + retirementDeductions; netPay = totalPay - totalDeductions; } // Calculating Net Pay for SkillLevel 1 with // hours worked > 40 if((skillLevel ==1) && (hoursWorked > 40)) { hourlyPayRate = LOW_PAY_RATE; regularPay = 40 * hourlyPayRate; overTimePay = hourlyPayRate*(hoursWorked - 40)*1.5; totalPay = regularPay + overTimePay; insuranceCost = 0.00; retirementDeductions = 0.00; totalDeductions = insuranceCost + retirementDeductions; netPay = totalPay - totalDeductions; } //Calculating the Net pay for Skill Level 2 with hours <= 40 if(skillLevel == 2) { if(hoursWorked <= 40)
  • 122. { hourlyPayRate = 20.00; regularPay = hoursWorked * hourlyPayRate; overTimePay = 0.00; totalPay = regularPay + overTimePay; switch(insuranceOption) { case 1: insuranceCost = 32.50; break; case 2: insuranceCost = 20.00; break; case 3: insuranceCost = 10.00; break; default: insuranceCost = 0.00; } retirementDeductions = 0.00; totalDeductions = insuranceCost + retirementDeductions; netPay = totalPay - totalDeductions; } } //Calculating the Net pay for Skill Level 2 with hours > 40 if((skillLevel == 2) && (hoursWorked > 40)) { hourlyPayRate = MEDIUM_PAY_RATE; regularPay = 40 * hourlyPayRate; overTimePay = 20.00*(hoursWorked - 40)*1.5; totalPay = regularPay + overTimePay; switch(insuranceOption) { case 1: insuranceCost = 32.50; break; case 2: insuranceCost = 20.00; break; case 3: insuranceCost = 10.00; break; default: insuranceCost = 0.00; } retirementDeductions = 0.00; totalDeductions = insuranceCost + retirementDeductions; netPay = totalPay - totalDeductions; } //Calculating the Net pay for Skill Level 3 with hours <= 40
  • 123. if(skillLevel == 3) { if(hoursWorked <= 40) { hourlyPayRate = HIGH_PAY_RATE; regularPay = hoursWorked * hourlyPayRate; overTimePay = 0.00; totalPay = regularPay + overTimePay; switch(insuranceOption) { case 1: insuranceCost = 32.50; break; case 2: insuranceCost = 20.00; break; case 3: insuranceCost = 10.00; break; default: insuranceCost = 0.00; } totalDeductions = insuranceCost + retirementDeductions; netPay = totalPay - totalDeductions; if(retirementOption ==1) retirementDeductions = 0.03 * netPay; else retirementDeductions = 0; totalDeductions = insuranceCost + retirementDeductions; netPay = totalPay - totalDeductions; } // Calculating the Net pay for Skill Level 3 with hours > 40 if(hoursWorked > 40) { hourlyPayRate = HIGH_PAY_RATE; regularPay = 40 * hourlyPayRate; overTimePay = 1.5*(hoursWorked - 40)*hourlyPayRate; totalPay = regularPay + overTimePay; switch(insuranceOption) { case 1: insuranceCost = 32.50; break; case 2: insuranceCost = 20.00; break; case 3: insuranceCost = 10.00; break; default:
  • 124. insuranceCost = 0.00; } totalDeductions = insuranceCost + retirementDeductions; netPay = totalPay - totalDeductions; if(retirementOption ==1) retirementDeductions = 0.03 * netPay; else retirementDeductions = 0; totalDeductions = insuranceCost + retirementDeductions; netPay = totalPay - totalDeductions; } } // If totalDeductions > totalPay, an error message is displayed. if(totalDeductions > totalPay) System.out.println("There is an Error !!! "); else //If totalDeductions < totalPay, the following items are displayed line by line. { System.out.println("Hours Worked = " + hoursWorked); System.out.println("Hourly Pay Rate = " + hourlyPayRate); System.out.println("Regular Pay = " + regularPay); System.out.println("OverTime pay = " + overTimePay); System.out.println("Gross Pay = " + totalPay); System.out.println("Total Deductions = " + totalDeductions); System.out.println("Net Pay = " + netPay); } } }
  • 125. 7. Create a class for Shutterbug’s Camera Store, which is having a digital camera sale. The class is named DigitalCamera, and it contains data fields for a brand, the number of megapixels in the resolution, and price. Include a constructor that takes arguments for the brand and megapixels. If the megapixel parameter is greater than 10, the constructor sets it to 10. The sale price is set based on the resolution; any camera with 6 megapixels or fewer is $99, and all other cameras are $129. Also include a method that displays DigitalCamera details. Write an application named TestDigitalCamera in which you instantiate at least four objects, prompt the user for values for the camera brand and number of megapixels, and display all the values. Save the files as DigitalCamera.java and TestDigitalCamera.java. C:UsersChristopherDocumentsNetBeansProjectsJRVampedsrcDigitalCamera.java // DigitalCamera class that will be used to instantiate objects in // TestDigitalCamera class. public class DigitalCamera //name of class { private String brand; //data field parameter entered by user private double mpixel; //data field parameter entered by user private double price; //Price not set by user, depends on the megapixel. //Write constructor that receives the brand and resolution parameters. public DigitalCamera(String manuf, double resolution) { brand = manuf; mpixel = resolution; if (mpixel <= 6) // If Camera Mpix <= 6, price = $99 { price = 99; } else { price = 129; // If camera Mpix > 6, price = $129 } if (mpixel >= 10) // All cameras with resolution >= 10 have their Mpix { // treated as 10 mpixel = 10; } } public String getBrand() { return brand; } public double getMpixel() { return mpixel; } public double getPrice() {
  • 126. return price; } public void setBrand(String manuf) { brand = manuf; } public void setMpixel(double resolution) { mpixel = resolution; } /* NOTE: Te set method is not needed in this app because it is determined by the value of the megapixel parameter. But the getPrice() is needed for other methods and instantiated objects that need to use this method public void setPrice(double amount) { price = amount; } */ public void cameraDetails() { System.out.println("Camera brand: "+ brand ); System.out.println("Resolution: " + mpixel + " MP"); System.out.println("Sales Price: $" + price); System.out.println("~~~~~~~~~~~~~~~"); } } C:UsersChristopherDocumentsNetBeansProjectsJRVampedsrcTestDigitalCamera.java // TestDigitalCamera class import java.util.Scanner; public class TestDigitalCamera { public static void main(String[] args) { Scanner keyboard = new Scanner(System.in); System.out.print("Enter 1st camera brand name: "); String brand = keyboard.next(); System.out.print("Enter camera resolution in MP: "); double mpixel = keyboard.nextDouble(); DigitalCamera canon = new DigitalCamera(brand, mpixel); // brand = brand1.getBrand(); // mpixel = brand1.getMpixel(); // double price = brand1.getPrice(); System.out.println("");
  • 127. canon.cameraDetails(); System.out.print("Enter 2nd camera brand name: "); String brand1 = keyboard.next(); System.out.print("Enter camera resolution in MP: "); double mpixel1 = keyboard.nextDouble(); DigitalCamera nikon = new DigitalCamera(brand1, mpixel1); System.out.println(""); nikon.cameraDetails(); System.out.print("Enter 3rd camera brand name: "); String brand2 = keyboard.next(); System.out.print("Enter camera resolution in MP: "); double mpixel2 = keyboard.nextDouble(); DigitalCamera sony = new DigitalCamera(brand2, mpixel2); System.out.println(""); sony.cameraDetails(); System.out.print("Enter 4th camera brand name: "); String brand3 = keyboard.next(); System.out.print("Enter camera resolution in MP: "); double mpixel3 = keyboard.nextDouble(); DigitalCamera olympus = new DigitalCamera(brand3, mpixel3); System.out.println(""); olympus.cameraDetails(); } }
  • 129. Q8, Page 293 (NOT COMPLETED: But you get the idea of what the solution should look like and how to get to it at the end) 8. Create a class for the Parks Department in Cloverdale. The class is named Park, and ito contains a String field for the name of the park, an integer field for the size in acres, and four Boolean fields that hold whether the park has each of these features: picnic facilities, a tennis court, a playground, and a swimming pool. Include get and set methods for each field. Include code in the method that sets the number of acres and does not allow a negative number or a number over 400. Save the file as Park.java. Then, create a program with methods that do the following:  Accepts a Park parameter and returns a Boolean value that indicates whether the Park has both picnic facilities and a playground.  Accepts a Park parameter and four Boolean parameters that represent requests for the previously mentioned Park features. The method returns true if the Park has all the requested features.  Accepts a Park parameter and four Boolean parameters that represent requests for the previously mentioned Park features. The method returns true if the Park has exactly all the requested features and no others.  Accepts a Park parameter and returns the number of facilities that the Park features.  Accepts two Park parameters and returns the larger Park. Declare at least three Park objects, and demonstrate that all the methods work correctly. Save the program as TestPark.java. // The NewPark class : Note the name has been changed from Park in thabove question to NewPark import java.util.Scanner; public class NewPark { private String parkName; private int parkAcres; private boolean hasPicnic; private boolean hasTennisCourt; private boolean hasPlayground; private boolean hasSwimming; private boolean hasallfeatures; public Scanner enter = new Scanner(System.in); public void setParkName(String park)
  • 130. { parkName = park; } public void setParkAcres() { int acres; String acresName; System.out.println("Enter the number of acres for park: "); acres = enter.nextInt(); if (acres < 0) { System.out.println("Acres is INVALID. Please enter a number greater than 0."); setParkAcres(); } else if (parkAcres > 400) { System.out.println("Acres is INVALID. Please enter a number less than 401."); setParkAcres(); } else { parkAcres = acres; } } public void setHasPicnic() { int picnic; System.out.println("Does park have picnic area?"); System.out.println("1 - YESn0 - NO"); picnic = enter.nextInt(); /*switch (picnic) { case 1: picnic = 1; hasPicnic = (1 > 0); break; case 2: picnic = 0; hasPicnic = (0 > 1); break;
  • 131. }*/ if (picnic == 1 ) { hasPicnic = true; } else if(picnic == 0) { hasPicnic = false; } } public void setHasTennisCourt() { int tennis; System.out.println("Does park have a Tennis Court?"); System.out.println("1 - YESn0 - NO"); tennis = enter.nextInt(); switch (tennis) { case 1: tennis = 1; hasTennisCourt = (1 > 0); break; case 2: tennis = 0; hasTennisCourt = (0 > 1); break; } } public void setHasPlayground() { int playground; System.out.println("Does park have a Playground?"); System.out.println("1 - YESn0 - NO"); playground = enter.nextInt(); switch (playground) { case 1: playground = 1; hasPlayground = (1 > 0); break; case 2: playground = 0; hasPlayground = (0 > 1);
  • 132. break; } } public void setHasSwimming() { int swimming; System.out.println("Does park have a Swimming Pool?"); System.out.println("1 - YESn0 - NO"); swimming = enter.nextInt(); switch (swimming) { case 1: swimming = 1; hasSwimming = (1 > 0); break; case 2: swimming = 0; hasSwimming = (0 > 1); break; } } public void biggerPark(String fpark, String spark,int fi, int si) { if(fi > si) { System.out.println(fpark+" is bigger than "+spark); } else { System.out.println(spark+" is bigger than "+fpark); } } public boolean hasallfeatures() { if (hasPicnic == hasTennisCourt == hasPlayground == hasSwimming == true) { return true; } else return false; } public String getParkName()
  • 133. { return parkName; } public int getParkAcres() { return parkAcres; } public boolean getHasPicnic() { return hasPicnic; } public boolean getHasTennisCourt() { return hasTennisCourt; } public boolean getHasPlayground() { return hasPlayground; } public boolean getHasSwimming() { return hasSwimming; } public boolean getallfeatures() { return hasallfeatures; } } //TestNewPark class package MyJavaLab2; import java.util.Scanner; public class TestNewPark { public static void main(String []args){ /* Park first = new Park(); first.setHasPicnic(); first.setHasPlayground();
  • 134. System.out.println(" Has picnic = "+first.getHasPicnic()); System.out.println(" Has playground = "+first.getHasPlayground());*/ //second question NewPark second = new NewPark(); Scanner input = new Scanner(System.in); System.out.println("ENTER PARK NAME"); String name = input.nextLine(); second.setParkName(name); second.setParkAcres(); System.out.println(" the park name "+second.getParkName()); System.out.println("the park Acres is "+second.getParkAcres()); second.setHasPicnic(); second.setHasPlayground(); second.setHasSwimming(); second.setHasTennisCourt(); System.out.println("Does the park "+name+" have all the features? "+second.hasallfeatures()); } }
  • 135. Page 294, Q9 9. a. Create a class named Invoice that holds an invoice number, balance due, and three fields representing the month, day, and year when the balance is due. Create a constructor that accepts values for all five data fields. Within the constructor, assign each argument to the appropriate field with the following exceptions: l If an invoice number is less than 1000, force the invoice number to 0. l If the month field is less than 1 or greater than 12, force the month field to 0. l If the day field is less than 1 or greater than 31, force the day field to 0. l If the year field is less than 2011 or greater than 2017, force the year field to 0. In the Invoice class, include a display method that displays all the fields on an Invoice object. Save the file as Invoice.java. b. Write an application containing a main() method that declares several Invoice objects, proving that all the statements in the constructor operate as specified. Save the file as TestInvoice.java. c. Modify the constructor in the Invoice class so that the day is not greater than 31, 30, or 28, depending on the month. For example, if a user tries to create an invoice for April 31, force it to April 30. Also, if the month is invalid, and thus forced to 0, also force the day to 0. Save the modified Invoice class as Invoice2.java. Then modify the TestInvoice class to create Invoice2 objects. Create enough objects to test every decision in the constructor. Save this file as TestInvoice2.java. //The Invoice class package MyJavaLab2; public class Invoice { private int InvoiceNumb; private double BalanceDue; private int Month; private int Day; private int Year; Invoice(int invoice,double balanceDue,int year,int month,int day) { if (invoice <1000) { this.InvoiceNumb = 0; } else { this.InvoiceNumb = invoice; } this.BalanceDue = balanceDue; if(year < 2011 || year > 2017) { this.Year = 0; } else {
  • 136. this.Year = year; } if (month < 1 || month > 12) { this.Month = 0; } else { this.Month = month; } if (day < 1 || day >31) { this.Day = 0; } else { this.Day = day; } } /** * @return the InvoiceNumb */ public int getInvoiceNumb() { return InvoiceNumb; } /** * @param InvoiceNumb the InvoiceNumb to set */ public void setInvoiceNumb(int InvoiceNumb) { if (InvoiceNumb <1000) { this.InvoiceNumb = 0; } else { this.InvoiceNumb = InvoiceNumb; } } /** * @return the BalanceDue */
  • 137. public double getBalanceDue() { return BalanceDue; } /** * @param BalanceDue the BalanceDue to set */ public void setBalanceDue(double BalanceDue) { this.BalanceDue = BalanceDue; } /** * @return the Month */ public int getMonth() { return Month; } /** * @param Month the Month to set */ public void setMonth(int Month) { if (Month < 1 || Month > 12) { this.Month = 0; } { this.Month = Month; } } /** * @return the Day */ public int getDay() { return Day; } /** * @param Day the Day to set */ public void setDay(int Day) { if (Day < 1 || Day >31) {
  • 138. this.Day = 0; } else { this.Day = Day; } } /** * @return the Year */ public int getYear() { return Year; } /** * @param Year the Year to set */ public void setYear(int Year) { if(Year < 2011 || Year > 2017) { this.Year = 0; } else { this.Year = Year; } } public String ReturnValue() { System.out.println("Invoice number is: " + this.InvoiceNumb + " and the balance due is: $" + this.BalanceDue); System.out.println("YEAR: " + this.Year + " MONTH: " + this.Month + " DAY: " + this.Day); System.out.println(); return this.InvoiceNumb +" $"+this.BalanceDue+ " the year due is " +this.Year +" the month is "+this.Month +" the day "+ this.Day; } } //Test Invoice class package MyJavaLab2; import java.util.Scanner; public class TestInvoice
  • 139. { public static void main(String []args) { Scanner input = new Scanner(System.in); System.out.println("ENTER INVOICE NUMBER "); int inviocenumb = input.nextInt(); System.out.println("ENTER BALANCE DUE "); double balancdue = input.nextDouble(); System.out.println("ENTER THE YEAR "); int year = input.nextInt(); System.out.println("ENTER THE MONTH "); int month = input.nextInt(); System.out.println("ENTER THE DAY "); int day = input.nextInt(); Invoice vice1 = new Invoice(inviocenumb,balancdue,year,month,day); vice1.getInvoiceNumb(); vice1.getBalanceDue(); vice1.getYear(); vice1.getMonth(); vice1.getDay(); System.out.println(vice1.ReturnValue()); }}
  • 141. EXL1 Consider an application in which you ask the user for a bank balance and then ask whether the user wants to see the balance after interest has accumulated. Each time the user chooses to continue, an increased balance appears, reflecting one more year of accumulated interest. When the user finally chooses to exit, the program ends. The program output is as shown at the end. C:UsersChristopherDocumentsNetBeansProjectsJRVampedsrcBankBalance.java import java.util.Scanner; public class BankBalance { public static void main(String[] args) { double balance; int response; int year = 1; final double INT_RATE = 0.03; Scanner keyboard = new Scanner(System.in); System.out.print("Enter initial bank balance > "); balance = keyboard.nextDouble(); System.out.println("Do you want to see next year's balance?"); System.out.print("Enter 1 for yes"); System.out.print(" or any other number for no >> "); response = keyboard.nextInt(); while(response == 1) { balance = balance + balance * INT_RATE; System.out.println("After year " + year + " at " + INT_RATE + " interest rate, balance is $" + balance); year = year + 1; System.out.println("nDo you want to see the balance " + "at the end of another year?"); System.out.print("Enter 1 for yes"); System.out.print(" or any other number for no >> "); response = keyboard.nextInt(); } } }
  • 142. EXL2 Suppose you want to display future bank balances while varying both years and interest rates. Figure 6-24 shows an application that contains an outer loop that varies interest rates between specified limits. At the start of the outer loop, the working balance is reset to its initial value so that calculations are correct for each revised interest rate value. The shaded inner loop varies the number of years and displays each calculated balance. Figure 6-25 shows a typical execution. C:UsersChristopherDocumentsNetBeansProjectsJRVampedsrcBankBalanceByRateAndByYear.java import java.util.Scanner; public class BankBalanceByRateAndByYear { public static void main(String[]args) { double initialBalance; double balance; int year; double interest; final double LOW = 0.02; final double HIGH = 0.05; final double INCREMENT = 0.01; final int MAX_YEAR = 4; Scanner keyboard = new Scanner(System.in); System.out.print("Enter initial bank balance > "); initialBalance = keyboard.nextDouble(); keyboard.nextLine(); for(interest = LOW; interest <= HIGH; interest += INCREMENT) { balance = initialBalance; System.out.println("nWith an initial balance of $" + balance + " at an interest of " + interest); for(year = 1; year <= MAX_YEAR; ++ year) { balance = balance + balance*interest; System.out.println("After year " + year + " balance is $" + balance); } } } }
  • 144. 3. Write an application that displays the factorial for every integer value from 1 to 10. A factorial of a number is the product of that number multiplied by each positive integer lower than it. For example, 4 factorial is 4 * 3 * 2 * 1, or 24. Save the file as Factorials.java. C:UsersChristopherDocumentsNetBeansProjectsJRVampedsrcFactorial.java public class Factorial { public static void main(String[] args) { int n = 10; int factorial = 1; int i; for(i=1; i<=n; ++i) { factorial = factorial * i; System.out.println("Factorial of " + i + " is: " + factorial); } } }
  • 145. Page 342 1. a. Write an application that counts by five from 5 through 200 inclusive, and that starts a new line after every multiple of 50 (50, 100, 150, and 200). Save the file as CountByFives.java. b. Modify the CountByFives application so that the user enters the value to count by. Start each new line after 10 values have been displayed. Save the file as CountByAnything.java. C:UsersChristopherDocumentsNetBeansProjectsJRVampedsrcCountByFives.java //This class counts un fives up to 200 and then display the results ten // on each line. The results obtained in the output can also be varied // by varying the value of the variable and the steps increment as needed. public class CountByFives { public static void main(String[] args) { int val; int count = 0; final int GROUPT = 10; for(val = 5; val <=211; val +=5) { count++; if(count % GROUPT ==0) { System.out.println(val + " " ); } else { System.out.print(val + " "); } } } }
  • 146. /*The code for question 1b is as shown below. The code is tested as foloows. The user wants to count in steps of 50 from 0 to any number say 1191 and display the results 20 per line. These 3 values are entered in turn with keyboard input. */ C:UsersChristopherDocumentsNetBeansProjectsJRVampedsrcCountByAnyThing.java import java.util.Scanner; public class CountByAnyThing { public static void main(String[] args) { int val; // the "INSTEPS OF" by which you want to count Scanner keyboard = new Scanner(System.in); System.out.print("Enter the maximum range of the number:> "); int value = keyboard.nextInt(); System.out.print("Enter the 'IN STEPS OF' by which you want to count:> "); int steps = keyboard.nextInt(); System.out.print("Enter the 'IN GROUPS OF' by which you want " + "the results displayed per line:> "); int groupt = keyboard.nextInt(); System.out.println(""); int count = 0; // counter variable for(val = steps; val <=value; val +=steps) { count++; if(count % groupt ==0) { System.out.println(val + " " ); } else { System.out.print(val + " "); } } System.out.println(""); } }
  • 147. Page 342, Q2: Write an application that asks a user to type an even number to continue or to type 999 to stop. When the user types an even number, display the message “Good job!” and then ask for another input. When the user types an odd number, display an error message and then ask for another input. When the user types 999, end the program. Save the file as EvenEntryLoop.java. C:UsersChristopherDocumentsNetBeansProjectsJRVampedsrcEvenEntryLoop.java import java.util.Scanner; public class EvenEntryLoop { public static void main(String[] args) { Scanner keyboard = new Scanner(System.in); System.out.print("Enter an EVEN number " + "to continue or 999 to STOP:> "); int entryValue = keyboard.nextInt(); while (entryValue != 999) { if (entryValue % 2 == 0) { System.out.print("Good job! "); System.out.print("Enter an EVEN number to " + "continue or 999 to STOP:> "); entryValue = keyboard.nextInt(); } else if(entryValue != 999) { System.out.print("Enter an EVEN number to " + "continue or 999 to STOP:> "); entryValue = keyboard.nextInt(); } } if (entryValue == 999) { System.out.print("PROGRAM ENDS" ); } } }
  • 149. Page 343, Q5. A knot is a unit of speed equal to one nautical mile per hour. Write an application that displays every integer knot value from 15 through 30 and its kilometers per hour and miles per hour equivalents. One nautical mile is 1.852 kilometers or 1.151 miles. Save the file as Knots.java. C:UsersChristopherDocumentsNetBeansProjectsJRVampedsrcKnots.java public class Knots { public static void main(String[] args) { int n = 15; // Maximum knots to conver double kms; double miles; //1 knot = 1.852km final double KM_FACTOR = 1.852; // 1 knot = 1.151 miles final double MILES_FACTOR = 1.1511; int i; System.out.println("Distances in knots & equivalents "); System.out.println( "in km and miles n"); for(i=1; i<=n; ++i) { kms = i * KM_FACTOR; miles = i * MILES_FACTOR; System.out.println( + i + " knots, = " + kms + (" kms; = ") + miles + " miles" ); } } }
  • 150. Page 343. Q6. Write an application that shows the sum of 1 to n for every n from 1 to 50. That is, the program displays 1 (the sum of 1 alone), 3 (the sum of 1 and 2), 6 (the sum of 1, 2, and 3), 10 (the sum of 1, 2, 3, and 4), and so on. Save the file as EverySum.java. //The following code gives the solution as a single line breaking through the screen. C:UsersChristopherDocumentsNetBeansProjectsJRVampedsrcEverySum.java public class EverySum { public static void main(String[] args) { int n; int sum = 0; for(n=1; n<=50; ++n) { sum = n + sum; System.out.print(sum +", "); // Output runs down the of the screen } } } ____________________________________________________ //The following code give the same output but with the resulting values // displayed in groups of 20 per line C:UsersChristopherDocumentsNetBeansProjectsJRVampedsrcEverySum2.java public class EverySum2 { public static void main(String[] args) { int n; int sum = 0; for(n=1; n<=50; ++n) { sum = n + sum; if(n % 20 ==0) { System.out.println(sum + " " ); } else { System.out.print(sum + " "); } } } }
  • 152. 4. Write an application that prompts a user for two integers and displays every integer between them. Display a message if there are no integers between the entered values. Make sure the program works regardless of which entered value is larger. Save the file as InBetween.java. C:UsersChristopherDocumentsNetBeansProjectsJRVampedsrcInBetweenNumbers.java import java.util.Scanner; public class InBetweenNumbers { public static void main(String[] args) { int x, y; //Declare two integer variables Scanner input = new Scanner(System.in); System.out.print("Enter the first integer:>> "); x = input.nextInt(); System.out.print("Enter the second integer:>> "); y = input.nextInt(); System.out.println("The numbers inbetween " + x + " and " +y + " are; "); if(x<y) { do { x = x+1; System.out.print(x + " "); } while (x<(y-1)); } else if(x>y) do { y = y+1; System.out.print(y + " "); } while (y<(x-1)); } }
  • 153. Page 343, Question 9 9. Write an application that prompts a user for a child’s current age and the estimated college costs for that child at age 18. Continue to reprompt a user who enters an age value greater than 18. Display the amount that the user needs to save each year until the child turns 18, assuming that no interest is earned on the money. For this application, you can assume that integer division provides a sufficient answer. Save the file as CollegeCost.java. C:UsersChristopherDocumentsNetBeansProjectsJRVampedsrcCollegeCost.java import java.util.Scanner; public class CollegeCost { public static void main(String[] args) { int collegeCost; //College cost at age 18 int age; // child's curent age final int ADDMISSION_AGE = 18; int annualSavings; //Average annual savings System.out.print("Enter college costs at age 18 year.> $"); Scanner input = new Scanner(System.in); collegeCost = input.nextInt(); System.out.print("Enter child's current age in years. > " ); Scanner keyboard = new Scanner(System.in); age = keyboard.nextInt(); while(age>18) { System.out.print("Please enter a valid age. >> "); age = input.nextInt(); } annualSavings = collegeCost/(ADDMISSION_AGE - age); System.out.println("You must save $" + annualSavings + " each year."); } }
  • 154. Page 344, Question 10 10. a. Write an application that prompts a user for the number of years the user has until retirement and the amount of money the user can save annually. If the user enters 0 or a negative number for either value, reprompt the user until valid entries are made. Assume that no interest is earned on the money. Display the amount of money the user will have at etirement. Save the file as RetirementGoal.java. C:UsersChristopherDocumentsNetBeansProjectsJRVampedsrcRetirementGoal.java import java.util.Scanner; public class RetirementGoal { public static void main(String[] args) { int yearsLeft; double annualSavings; double retirementSavings; Scanner input = new Scanner(System.in); System.out.print("Enter number of years before retirement:> "); yearsLeft = input.nextInt(); while(yearsLeft<=0) { System.out.print("Please enter a valid number of years left.> "); yearsLeft = input.nextInt(); } System.out.print("Enter annual savings in $;> "); annualSavings = input.nextDouble(); while(annualSavings<=0) { System.out.print("Please enter a value > 0 for your annual savings> "); annualSavings = input.nextDouble(); } retirementSavings = yearsLeft * annualSavings; System.out.println(""); System.out.println("Retirement savings = $" + retirementSavings); } }
  • 155. Page 433, Q1. Write an application that stores 12 integers in an array. Display the integers from first to last, and then display the integers from last to first. Save the file as TwelveInts.java. package MyJavaLab3; public class TwelveInts { public static void main(String[] args) { int[] twelveNums = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}; int x; System.out.print("The numbers in ascending order are: "); for(x=0; x < twelveNums.length; ++x) { System.out.print(twelveNums[x] + ","); } System.out.println(""); System.out.println(""); System.out.print("The numbers in descending order are: "); for(x= 0; x < twelveNums.length; ++x) { System.out.print(twelveNums[11-x] + ","); } System.out.println(""); } }
  • 156. C:UsersChristopherDocumentsNetBeansProjectsJRVampedsrcCompareStrings.java // This example demonstrate how to compare strings import java.util.Scanner; public class CompareStrings { public static void main(String[] args) { String aName = "Carmen"; String anotherName; Scanner input = new Scanner(System.in); System.out.print("Enter your name > "); anotherName = input.nextLine(); if(aName.equals(anotherName)) System.out.println(aName + " equals " + anotherName); else System.out.println(aName + " does not equal " + anotherName); } }
  • 157. C:UsersChristopherDocumentsNetBeansProjectsJRVampedsrcBusinessLetter.java /* Tthe application prompts the user for a customer’s first and last names. The application then extracts these names so that a friendly business letter can be constructed. After the application prompts the user to enter a name, a loop control variable is initialized to 0. While the variable remains less than the length of the entered name, each character is compared to the space character. When a space is found, two new strings are created. The first, firstName, is the substring of the original entry from position 0 to the location where the space was found. The second, familyName, is the substring of the original entry from the position after the space to the end of the string. Once the first and last names have been created, the loop control variable is set to the length of the original string so the loop will exit and proceed to the display of the friendly business letter. */ import javax.swing.*; public class BusinessLetter { public static void main(String[] args) { String name; String firstName = ""; String familyName = ""; int x; char c; name = JOptionPane.showInputDialog(null, "Please enter customer's first and last name"); x = 0; while(x < name.length()) { if(name.charAt(x) == ' ') { firstName = name.substring(0, x); familyName = name.substring(x + 1, name.length()); x = name.length(); } ++x; } JOptionPane.showMessageDialog(null, "Dear " + firstName + ",nI am so glad we are on a first name basis" + "nbecause I would like the opportunity to" + "ntalk to you about an affordable insurance" + "nprotection plan for the entire " + familyName + "nfamily. Call A-One Family Insurance today" + "nat 1-800-555-9287."); } }
  • 159. C:UsersChristopherDocumentsNetBeansProjectsJRVampedsrcRepairName.java /* Using String Methods To demonstrate the use of the String methods, in this section you create an application that asks a user for a name and then “fixes” the name so that the first letter of each new word is uppercase, whether the user entered the name that way or not. 1. Open a new text file in your text editor. Enter the following first few lines of a RepairName program. The program declares several variables, including two strings that will refer to a name: one will be “repaired” with correct capitalization; the other will be saved as the user entered it so it can be displayed in its original form at the end of the program. After declaring the variables, prompt the user for a name: */ import javax.swing.*; public class RepairName { public static void main(String[] args) { String name; String saveOriginalName; int stringLength; int i; char c; name = JOptionPane.showInputDialog(null, "Please enter your first and last name"); /* 2. Store the name entered in the saveOriginalName variable. Next, calculate the length of the name the user entered, then begin a loop that will examine every character in the name. The first character of a name is always capitalized, so when the loop control variable i is 0, the character in that position in the name string is extracted and converted to its uppercase equivalent. Then the name is replaced with the uppercase character appended to the remainder of the existing name. */ saveOriginalName = name; stringLength = name.length(); for(i = 0; i < stringLength; i++) { c = name.charAt(i); if(i == 0) { c = Character.toUpperCase(c); name = c + name.substring(1, stringLength); } /* 3. After the first character in the name is converted, the program looks through the rest of the name, testing for spaces and capitalizing every character that follows a space. When a space is found at position i, i is increased, the next character is extracted from the name, the
  • 160. character is converted to its uppercase version, and a new name string is created using the old string up to the current position, the newly capitalized letter, and the remainder of the name string. The if…else ends and the for loop ends. */ else if(name.charAt(i) == ' ') { ++i; c = name.charAt(i); c = Character.toUpperCase(c); name = name.substring(0, i) + c + name.substring(i + 1, stringLength); } } /* 4. After every character has been examined, display the original and repaired names, and add closing braces for the main() method and the class. */ JOptionPane.showMessageDialog(null, "Original name was " + saveOriginalName + "nRepaired name is " + name); } }
  • 161. C:UsersChristopherDocumentsNetBeansProjectsJRVampedsrcNumberInput.java /* Converting a String to an Integer In the next steps, you write a program that prompts the user for a number, reads characters from the keyboard, stores the characters in a String, and then converts the String to an integer that can be used in arithmetic statements. 1. Open a new text file in your text editor. Type the first few lines of a NumberInput class that will accept string input: */ import javax.swing.*; public class NumberInput { public static void main(String[] args) { /* 2. Declare the following variables for the input String, the integer to which it is converted, and the result: */ String inputString; int inputNumber; int result; /* 3. Declare a constant that holds a multiplier factor. This program will multiply the user’s input by 10: */ final int FACTOR = 10; /* 4. Enter the following input dialog box statement that stores the user keyboard input in the String variable inputString: */ inputString = JOptionPane.showInputDialog(null, "Enter a number"); /* 5. Use the following Integer.parseInt() method to convert the input String to an integer. Then multiply the integer by 10 and display the result: */ inputNumber = Integer.parseInt(inputString); result = inputNumber * FACTOR; JOptionPane.showMessageDialog(null, inputNumber + " * " + FACTOR + " = " + result); /* 6. Add the final two closing curly braces for the program, then save the program as NumberInput.java and compile and test the program. Figure 7-11 shows a typical execution. Even though the user enters a String, it can be used successfully in an arithmetic statement because it was converted using the parseInt() method. */ } }
  • 163. C:UsersChristopherDocumentsNetBeansProjectsJRVampedsrcFindPrice.java /* Using Parallel Arrays : As an added bonus, if you set up another array with the same number of elements and corresponding data, you can use the same subscript to access additional information. A parallel array is one with the same number of elements as another, and for which the values in corresponding elements are related. For example, if the 10 items your company carries have 10 different prices, you can set up an array to hold those prices as follows: double[] prices = {0.29, 1.23, 3.50, 0.69…}; The prices must appear in the same order as their corresponding item numbers in the validValues array. Now, the same for loop that finds the valid item number also finds the price, as shown in the application in Figure 8-9. In the shaded portion of the code, notice that when the ordered item’s number is found in the validValues array, the itemPrice value is “pulled” from the prices array. In other words, if the item number is found in the second position in the validValues array, you can find the correct price in the second position in the prices array. Figure 8-10 shows a typical execution of the program. A user requests item 409, which is the eighth element in the validValues array, so the price displayed is the eighth element in the prices array. */ import javax.swing.*; public class FindPrice { public static void main(String[] args) { final int NUMBER_OF_ITEMS = 10; int[] validValues = {101, 108, 201, 213, 266, 304, 311, 409, 411, 412}; double[] prices = {0.29, 1.23, 3.50, 0.69, 6.79, 3.19, 0.99, 0.89, 1.26, 8.00}; String strItem; int itemOrdered; double itemPrice = 0.0; boolean validItem = false; strItem = JOptionPane.showInputDialog(null, "Enter the item number you want to order"); itemOrdered = Integer.parseInt(strItem); for(int x = 0; x < NUMBER_OF_ITEMS; ++x) { if(itemOrdered == validValues[x]) { validItem = true; itemPrice = prices[x]; } } if(validItem) JOptionPane.showMessageDialog(null, "The price for item " + itemOrdered + " is $" + itemPrice); else JOptionPane.showMessageDialog(null, "Sorry - invalid item entered"); } }
  • 165. As an example of how useful two-dimensional arrays can be, assume that you own an apartment building with four floors—a basement, which you refer to as floor zero, and three other floors numbered one, two, and three. In addition, each of the floors has studio (with no bedroom) and one- and two-bedroom apartments. The monthly rent for each type of apartment is different—the higher the floor, the higher the rent (the view is better), and the rent is higher for apartments with more bedrooms. Table 9-1 shows the rental amounts. To determine a tenant’s rent, you need to know two pieces of information: the floor on which the tenant rents an apartment and the number of bedrooms in the apartment. Within a Java program, you can declare an array of rents using the following code: int[][] rents = {{400, 450, 510}, {500, 560, 630}, {625, 676, 740}, {1000, 1250, 1600}}; If you declare two integers named floor and bedrooms, then any tenant’s rent can be referred to as rents[floor][bedrooms]. Figure 9-10 shows an application that prompts a user for a floor number and number of bedrooms. A typical execution follows next. C:UsersChristopherDocumentsNetBeansProjectsJDMay2018srcFindRent.java import javax.swing.*; class FindRent { public static void main(String[] args) { int[][] rents = { {400, 450, 510}, {500, 560, 630}, {625, 676, 740}, {1000, 1250, 1600} }; String entry; int floor; int bedrooms; entry = JOptionPane.showInputDialog(null, "Enter a floor number "); floor = Integer.parseInt(entry); entry = JOptionPane.showInputDialog(null, "Enter number of bedrooms "); bedrooms = Integer.parseInt(entry); JOptionPane.showMessageDialog(null, "The rent for a " + bedrooms + " bedroom apartment on floor " + floor + " is $" + rents[floor][bedrooms]); } }
  • 166. Below is an application that uses the length fields associated with the rents array to display all the rents. The floor variable varies from 0 through one less than 4 in the outer loop, and the bdrms variable varies from 0 through one less than 3 in the inner loop. The output is shown next. C:UsersChristopherDocumentsNetBeansProjectsJDMay2018srcDisplayRents.java class DisplayRents { public static void main(String[] args) { int[][] rents = { {400, 450, 510}, {500, 560, 630}, {625, 676, 740}, {1000, 1250, 1600} }; int floor; int bdrms; for(floor = 0; floor < rents.length; ++floor) for(bdrms = 0; bdrms < rents[floor].length; ++bdrms) System.out.println("Floor " + floor + " Bedrooms " + bdrms + " Rent is $" + rents[floor][bdrms]); } }
  • 168. You can declare an enumerated type in its own file, in which case the filename matches the type name and has a .java extension. You will use this approach in a “You Do It” exercise later in this chapter. Alternatively, you can declare an enumerated type within a class, but not within a method. Figure 9-24 is an application that declares a Month enumeration and demonstrates its use. Figure 9-25 shows two typical executions. C:UsersChristopherDocumentsNetBeansProjectsJRVampedsrcEnumDemo.java import java.util.Scanner; public class EnumDemo { enum Month {JAN, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV, DEC}; public static void main(String[] args) { Month birthMonth; String userEntry; int position; int comparison; Scanner input = new Scanner(System.in); System.out.println("The months are:"); for(Month mon : Month.values()) System.out.print(mon + " "); System.out.print("nnEnter the first three letters of " + "your birth month >> "); userEntry = input.nextLine().toUpperCase(); birthMonth = Month.valueOf(userEntry); System.out.println("You entered " + birthMonth); position = birthMonth.ordinal(); System.out.println(birthMonth + " is in position " + position); System.out.println("So its month number is " + (position + 1)); comparison = birthMonth.compareTo(Month.JUN); if(comparison < 0) System.out.println(birthMonth + " is earlier in the year than " + Month.JUN); else if(comparison > 0) System.out.println(birthMonth + " is later in the year than " + Month.JUN); else System.out.println(birthMonth + " is " + Month.JUN); } }
  • 170. You can use enumerations to control a switch structure. Figure 9-26 contains a class that declares a Property enumeration for a real estate company. The program assigns one of the values to a Property variable and then uses a switch structure to display an appropriate message. Figure 9-27 shows the result. C:UsersChristopherDocumentsNetBeansProjectsJRVampedsrcEnumDemo2.java import java.util.Scanner; public class EnumDemo2 { enum Property {SINGLE_FAMILY, MULTIPLE_FAMILY, CONDOMINIUM, LAND, BUSINESS}; public static void main(String[] args) { Property propForSale = Property.MULTIPLE_FAMILY; switch(propForSale) { case SINGLE_FAMILY: case MULTIPLE_FAMILY: System.out.println("Listing fee is 5%"); break; case CONDOMINIUM: System.out.println("Listing fee is 6%"); break; case LAND: case BUSINESS: System.out.println ("We do not handle this type of property"); } } } Creating an enumeration type provides you with several advantages. For example, the Month enumeration improves your programs in the following ways:  If you did not create an enumerated type for month values, you could use another type— for example, ints or Strings. The problem is that any value could be assigned to an int or String variable, but only the 12 allowed values can be assigned to a Month.  If you did not create an enumerated type for month values, you could create another type to represent months, but invalid behavior could be applied to the values. For example, if you used integers to represent months, you could add, subtract, multiply, or divide two months, which is not logical. Programmers say using enums makes the values type-safe. Type-safe describes a data type for which only appropriate behaviors are allowed.  The enum constants provide a form of self-documentation. Someone reading your program might misinterpret what 9 means as a month value, but there is less confusion when you use the identifier OCT.  As with other classes, you can also add methods and other fields to an enum type.
  • 171. Using Part of an Array Sometimes, you do not want to use every value in an array. For example, suppose that you write a program that allows a student to enter up to 10 quiz scores and then computes and displays the average. To allow for 10 quiz scores, you create an array that can hold 10 values, but because the student might enter fewer than 10 values, you might use only part of the array. The code below shows such a program. C:UsersChristopherDocumentsNetBeansProjectsJRVampedsrcFlexibleQuizAverage.java import java.util.*; public class AverageOfQuizzes { public static void main(String[] args) { int[] scores = new int[10]; int score = 0; int count = 0; int total = 0; final int QUIT = 999; final int MAX = 10; Scanner input = new Scanner(System.in); System.out.print("Enter quiz score or " + QUIT + " to quit >> "); score = input.nextInt(); while(score != QUIT) { scores[count] = score; total += scores[count]; ++count; if(count == MAX) score = QUIT; else { System.out.print("Enter next quiz score or " + QUIT + " to quit >> "); score = input.nextInt(); } } System.out.print("nThe scores entered were: "); for(int x = 0; x < count; ++x) System.out.print(scores[x] + " "); if(count != 0) System.out.println("n The average is " + (total * 1.0 / count)); else System.out.println("No scores were entered."); } }
  • 173. Ch9; EX1; Page 446 Using a Bubble Sort In this section, you create a program in which you enter values that you sort using the bubble sort algorithm. You display the values during each iteration of the outer sorting loop so that you can track the values as they are repositioned in the array. package MyJavaLab4; import java.util.Scanner; class BubbleSortDemo { public static void main(String[] args) /* Declare an array of 5 integers and a variable to control the number of comparissons to make during the sort. Declare a Scanner object, two integers to use as subscripts for handling the array, and a temporary integer value to use during the sort. */ { int[] someNums = new int[5]; int comparisonsToMake = someNums.length - 1; Scanner keyboard = new Scanner(System.in); int a, b, temp; /* Next is a for loop that prompts user for a value for each array element and accepts them. */ for(a = 0; a < someNums.length; ++a) { System.out.print("Enter number " + (a + 1) + " >> "); someNums[a] = keyboard.nextInt(); } /* Next, call a method that accepts the array and the number of sort iterations performed so far, which is 0. The purpose of the method is to display the current status of the array as it is being sorted. */
  • 174. display(someNums, 0); /* Add the nested loops that perform the sort. The outer loop controls the number of passes through the list, and the inner loop controls the comparisons on each pass through the list. When any two adjacent elements are out of order, they are swapped. At the end of the nested loop, the current list is output and the number of comparisons to be made on the next pass is reduced by one. */ for(a = 0; a <someNums.length -1; ++a) { for(b = 0; b < comparisonsToMake; ++b) { if(someNums[b] > someNums[b+1]) { temp = someNums[b]; someNums[b] =someNums[b+1]; someNums[b+1] = temp; } } display(someNums, (a+1)); --comparisonsToMake; } /* After the closing brace for the main() method, but before the closing brace for the class, insert the display() method. It accepts the array and the current outer loop index, and it displays the array contents. */ } public static void display(int[] someNums, int a) { System.out.print("Iteration "+ a + "; "); for(int x = 0; x < someNums.length; ++x) System.out.print(someNums[x] + " "); System.out.println(); } /*
  • 175. Notice that after the first iteration, the largest value has sunk to the bottom of the list. After the second iteration, the two largest values are at the bottom of the list, and so on. */ } The previous lines of code are now modified so that the user can enter an array of any length for sorting. First, the user indicate the length, i, of the array from the beginning. The implementation was demonstrated with an array length of 9 elements. The line of codes that specify the array length is highlighted in blue. package MyJavaLab4; import java.util.Scanner; class BubbleSortDemo { public static void main(String[] args) /* Declare an array of 5 integers and a variable to control the number of comparissons to make during the sort. Declare a Scanner object, two integers to use as subscripts for handling the array, and a temporary integer value to use during the sort. */ { Scanner keyboard = new Scanner(System.in); System.out.print("Enter the length of the array, i = "); int i = keyboard.nextInt(); int[] someNums = new int[i]; int comparisonsToMake = someNums.length - 1; int a, b, temp;
  • 176. /* Next is a for loop that prompts user for a value for each array element and accepts them. */ for(a = 0; a < someNums.length; ++a) { System.out.print("Enter number " + (a + 1) + " >> "); someNums[a] = keyboard.nextInt(); } /* Next, call a method that accepts the array and the number of sort iterations performed so far, which is 0. The purpose of the method is to display the current status of the array as it is being sorted. */ display(someNums, 0); /* Add the nested loops that perform the sort. The outer loop controls the number of passes through the list, and the inner loop controls the comparisons on each pass through the list. When any two adjacent elements are out of order, they are swapped. At the end of the nested loop, the current list is output and the number of comparisons to be made on the next pass is reduced by one. */ for(a = 0; a <someNums.length -1; ++a) { for(b = 0; b < comparisonsToMake; ++b) { if(someNums[b] > someNums[b+1]) { temp = someNums[b]; someNums[b] =someNums[b+1]; someNums[b+1] = temp; } } display(someNums, (a+1));
  • 177. --comparisonsToMake; } /* After the closing brace for the main() method, but before the closing brace for the class, insert the display() method. It accepts the array and the current outer loop index, and it displays the array contents. */ } public static void display(int[] someNums, int a) { System.out.print("Iteration "+ a + "; "); for(int x = 0; x < someNums.length; ++x) System.out.print(someNums[x] + " "); System.out.println(); } /* Notice that after the first iteration, the largest value has sunk to the bottom of the list. After the second iteration, the two largest values are at the bottom of the list, and so on. */ }
  • 178. EXAMPLE demonstrating the creation of a Superclass and an application to use it page 498 //Party Class C:UsersChristopherDocumentsNetBeansProjectsJRVampedsrcParty.java public class Party { private int guests; // private field // public get and set methods public int getGuests() { return guests; } public void setGuests(int numGuests) { guests = numGuests; } // Method that displays a party invitation public void displayInvitation() { System.out.println("Please come to my party! "); } } //Writig an Application that uses the Party class : UseParty.java C:UsersChristopherDocumentsNetBeansProjectsJRVampedsrcUseParty.java import java.util.Scanner; public class UseParty { public static void main(String[] args) { // Declare variables for the number of guests, a Party objects // and a Scanner object for user input. int guests; Party aParty = new Party(); Scanner keyboard = new Scanner(System.in);
  • 179. System.out.print("Enter the number of guests for the party:> "); guests = keyboard.nextInt(); aParty.setGuests(guests); System.out.println("The party has " + aParty.getGuests() + " guests."); aParty.displayInvitation(); } } //Creating a Subclass from the Party class: DinnerParty.java C:UsersChristopherDocumentsNetBeansProjectsJRVampedsrcDinnerParty.java public class DinnerParty extends Party { // private field particular to DinnerParty class // The other fields are already defined in the Party class private int dinnerChoice; // get and set methods for dinnerChoice field public int getDinnerChoice() { return dinnerChoice; } public void setDinnerChoice(int choice) { dinnerChoice = choice; } } //Creating an Application that uses the DinnerParty class; UseDinnerParty.java C:UsersChristopherDocumentsNetBeansProjectsJRVampedsrcUseDinnerParty.java import java.util.Scanner; public class UseDinnerParty { public static void main(String[] args) { // Declare variables for the number of guests, a Party objects // and a Scanner object for user input. int guests; int choice; Party aParty = new Party(); DinnerParty aDinnerParty = new DinnerParty(); Scanner keyboard = new Scanner(System.in); System.out.print("Enter the number of guests for the party:> "); guests = keyboard.nextInt(); aParty.setGuests(guests); System.out.println("The party has " + aParty.getGuests() + " guests."); aParty.displayInvitation(); System.out.print("nEnter the number of guests for the dinner party:> "); guests = keyboard.nextInt();
  • 180. aDinnerParty.setGuests(guests); System.out.print("Enter the menu option --- 1 for chicken and 2 for beef:>n "); choice = keyboard.nextInt(); aDinnerParty.setDinnerChoice(choice); System.out.println("The dinner party has " + aDinnerParty.getGuests() + " guests."); System.out.println("Menu option " + aDinnerParty.getDinnerChoice() + " will be served. "); aDinnerParty.displayInvitation(); } }
  • 181. Exception Handling Examples C:UsersChristopherDocumentsNetBeansProjectsJRVampedsrcDivisionMistakeCaught.java /* The main() method in the class contains a try block with code that attempts division.When illegal integer division is attempted, an ArithmeticException is automatically created and the catch block executes. */ import java.util.Scanner; public class DivisionMistakeCaught { public static void main(String[] args) { Scanner input = new Scanner(System.in); int numerator, denominator, result; System.out.print("Enter numerator:>> "); numerator = input.nextInt(); System.out.print("Enter denomiator:>> "); denominator = input.nextInt(); try { result = numerator / denominator; System.out.println(numerator + " / " + denominator + " = " + result); } catch(ArithmeticException mistake) { System.out.print(mistake.getMessage()); } System.out.println(" End of program"); } }
  • 182. C:UsersChristopherDocumentsNetBeansProjectsJRVampedsrcEnteringIntegers.java /* to add a nextLine() call after any next(), nextInt(), or nextDouble() call to absorb the Enter key remaining in the input buffer before subsequent nextLine() calls. When you attempt to convert numeric data in a try block and the effort is followed by another attempted conversion, you also must remember to account for the potential remaining characters left in the input buffer. This program accepts and displays an array of six integers. */ import java.util.Scanner; public class EnteringIntegers { public static void main(String[] args) { int[] numberList = {0, 0, 0, 0, 0, 0}; int x; Scanner input = new Scanner(System.in); for(x = 0; x < numberList.length; ++x) { try { System.out.print("Enter an integer >>: "); numberList[x] = input.nextInt(); } catch(Exception e) { System.out.println("Exception occured"); } // input.nextLine(); // After the first run, uncomment the above // line & re-run. Notice how the program responds } System.out.print("The numbers are: "); for(x = 0; x < numberList.length; ++x) System.out.print(numberList[x] + " " ); System.out.println(" "); } }
  • 183. Throwing and Catching Multiple Exceptions You can place as many statements as you need within a try block, and you can catch as many exceptions as you want. If you try more than one statement, only the first error-generating statement throws an exception. As soon as the exception occurs, the logic transfers to the catch block, which leaves the rest of the statements in the try block unexecuted. When a program contains multiple catch blocks, they are examined in sequence until a match is found for the type of exception that occurred. Then, the matching catch block executes, and each remaining catch block is bypassed. For example, consider the application in Figure 12-18. The main() method in the DivisionMistakeCaught3 class throws two types of Exception objects: an ArithmeticException and an InputMismatchException. The try block in the application surrounds all the statements in which the exceptions might occur. C:UsersChristopherDocumentsNetBeansProjectsJRVampedsrcDivisionMistakeCaught3.java import java.util.*; public class DivisionMistakeCaught3 { public static void main(String[] args) { Scanner input = new Scanner(System.in); int numerator, denominator, result; try { System.out.print("Enter numerator >> "); numerator = input.nextInt(); System.out.print("Enter denominator >> "); denominator = input.nextInt(); result = numerator / denominator; System.out.println(numerator + " / " + denominator + " = " + result); } catch(ArithmeticException mistake) { System.out.println(mistake.getMessage()); } catch(InputMismatchException mistake) { System.out.println("Wrong data type"); } System.out.println("End of program"); } }
  • 185. /* INCLUDING JCheckBoxes in an Application – page 776 Create an interactive program for a resort. The base price for a room is $200, and a guest can choose from several options. Reserving a room for a weekend night adds $100 to the price, including breakfast adds $20, and including a round of golf adds $75. A guest can select none, some, or all of these premium additions. Each time the user changes the option package, the price is recalculated. 1. Open a new file, and then type the following first few lines of a Swing application that demonstrates the use of a JCheckBox. Note that the JResortCalculator class implements the ItemListener interface: */ package MyGUIx; import javax.swing.*; import java.awt.*; import java.awt.event.*; public class JResortCalculator extends JFrame implements ItemListener { /* 2. Declare the named constants that hold the base price for a resort room and the premium amounts for a weekend stay, including breakfast and a round of golf. Also include a variable that holds the total price for the stay, and initialize it to the value of the base price. Later, depending on the user’s selections, premium fees might be added to totalPrice, making it more than BASE_PRICE. */ final int BASE_PRICE = 200; final int WEEKEND_PREMIUM = 100; final int BREAKFAST_PREMIUM = 20; final int GOLF_PREMIUM = 75; int totalPrice = BASE_PRICE; /* 3. Declare three JCheckBox objects. Each is labeled with a String that contains a description of the option and the cost of the option. Each JCheckBox starts unchecked or deselected. */ JCheckBox weekendBox = new JCheckBox("Weekend premium $" + WEEKEND_PREMIUM, false); JCheckBox breakfastBox = new JCheckBox("Breakfast $" + BREAKFAST_PREMIUM, false); JCheckBox golfBox = new JCheckBox("Golf $" + GOLF_PREMIUM, false); /* 4. Include JLabels to hold user instructions and information and a JTextField in which to display the total price: */ JLabel resortLabel = new JLabel("Resort Price Calculator");
  • 186. JLabel priceLabel = new JLabel("The price for your stay is"); JTextField totPrice = new JTextField(4); JLabel optionExplainLabel = new JLabel("Base price for a room is $" + BASE_PRICE + "."); JLabel optionExplainLabel2 = new JLabel("Check the options you want"); /* 5. Begin the JResortCalculator class constructor. Include instructions to set the title by passing it to the JFrame parent class constructor, to set the default close operation, and to set the layout manager. Then add all the necessary components to the JFrame. */ public JResortCalculator() { super("Resort Price Calculator"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLayout(new FlowLayout()); add(resortLabel); add(optionExplainLabel); add(optionExplainLabel2); add(weekendBox); add(breakfastBox); add(golfBox); add(priceLabel); add(totPrice); /* 6. Continue the constructor by setting the text of the totPrice JTextField to display a dollar sign and the totalPrice value. Register the class as a listener for events generated by each of the three JCheckBoxes. Finally, add a closing curly brace for the constructor. */ totPrice.setText("$" + totalPrice); weekendBox.addItemListener(this); breakfastBox.addItemListener(this); golfBox.addItemListener(this); } /* 7. Begin the itemStateChanged() method that executes when the user selects or deselects a JCheckBox. Use the appropriate methods to determine which JCheckBox is the source of the current ItemEvent and whether the event was generated by selecting a JCheckBox or by deselecting one. */ @Override public void itemStateChanged(ItemEvent event) { Object source = event.getSource(); int select = event.getStateChange();
  • 187. /* 8. Write a nested if statement that tests whether the source is equivalent to the weekendBox, breakfastBox, or, by default, the golfBox. In each case, depending on whether the item was selected or deselected, add or subtract the corresponding premium fee from the totalPrice. Display the total price in the JTextField, and add a closing curly brace for the method. */ if(source == weekendBox) if(select ==ItemEvent.SELECTED) totalPrice += WEEKEND_PREMIUM; else totalPrice -= WEEKEND_PREMIUM; else if(source == breakfastBox) { if(select == ItemEvent.SELECTED) totalPrice += BREAKFAST_PREMIUM; else totalPrice -= BREAKFAST_PREMIUM; } else//if(source == golfBox) by default if(select == ItemEvent.SELECTED) totalPrice += GOLF_PREMIUM; else totalPrice -= GOLF_PREMIUM; totPrice.setText("$" + totalPrice); } /* 9. Add a main() method that creates an instance of the JFrame and sets its size and visibility. Then add a closing curly brace for the class. */ public static void main(String[] args) { JResortCalculator aFrame = new JResortCalculator(); final int WIDTH = 300; final int HEIGHT = 200; aFrame.setSize(WIDTH, HEIGHT); aFrame.setVisible(true); } } /* 10. Save the file as JResortCalculator.java. Compile and execute the application. The output appears in Figure 14-41 with the base price initially set to $200. */
  • 189. Scene Builder Example (Gaddis page 998 – 1016) Summary of Creating a JavaFX Application Here is a broad summary of the steps that you take when creating a JavaFX application  Use Scene Builder to design the GUI. Be sure to give an fx:id to all of the components that you plan to access in your Java code. Save the GUI as an FXML file.  Write the code for the main application class, which loads the FXML file and launches the application. Save and compile the code in the same location as the FXML file.  Write the code for the controller class, which contains the event handler methods for the GUI. Save and compile the code in the same location as the FXML file.s  In Scene Builder, register the controller class, then register an event handler method for each component that needs to respond to events. Save the FXML file again. NOTE: All the the 3 files must be in the same folder. KiloConverter.fxml (Created in Scene Builder. To open in NetBeans, right click and select edit.) KiloConverterController.java KiloCnntroller.java (The main program) KiloConverter.fxml file C:UsersChristopherDocumentsNetBeansProjectsJavaOPS_2019srcKilo meterConverter.fxml <?xml version="1.0" encoding="UTF-8"?> <?import javafx.scene.control.*?> <?import java.lang.*?> <?import javafx.scene.layout.*?> <AnchorPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="206.0" prefWidth="467.0" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1" fx:controller="KilometerConverterController"> <children> <Label fx:id="promptLabel" layoutX="35.0" layoutY="53.0" text="Enter a distance in kilometers" /> <TextField fx:id="kilometerTextField" layoutX="336.0" layoutY="46.0" prefHeight="45.0" prefWidth="116.0" /> <Label fx:id="outputLabel" layoutX="35.0" layoutY="92.0" prefHeight="39.0" prefWidth="323.0" />
  • 190. <Button fx:id="convertButton" layoutX="28.0" layoutY="140.0" mnemonicParsing="false" onAction="#convertButtonListener" text="Convert to miles" /> </children> </AnchorPane> KiloConverterController.java file C:UsersChristopherDocumentsNetBeansProjectsJavaOPS_2019srcKilo meterConverterController.java import javafx.fxml.FXML; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.control.TextField; public class KilometerConverterController { @FXML private Button convertButton; @FXML private TextField kilometerTextField; @FXML private Label outputLabel; @FXML private Label promptLabel; // This optional method is called when the FXML file is loaded. public void initialize() { // Perform any necessary initialization here. } // Event listener for the convertButton public void convertButtonListener() { final double CONVERSION_FACTOR = 0.6214; // Get the kilometers from the TextField. String str = kilometerTextField.getText(); // Convert kilometers to miles.
  • 191. double miles = Double.parseDouble(str) * CONVERSION_FACTOR; // Display the converted distance. outputLabel.setText(str + " kilometers is " + miles + " miles."); } } KiloConverter.java file C:UsersChristopherDocumentsNetBeansProjectsJavaOPS_2019srcKilo meterConverter.java import javafx.application.Application; import javafx.fxml.FXMLLoader; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.stage.Stage; public class KilometerConverter extends Application { public void start(Stage stage) throws Exception { // Load the FXML file. Parent parent = FXMLLoader.load(getClass().getResource("KilometerConverter.fxml")); // Build the scene graph. Scene scene = new Scene(parent); // Display our window, using the scene graph. stage.setTitle("Kilometer Converter"); stage.setScene(scene); stage.show(); } public static void main(String[] args) { // Launch the application. launch(args); } }
  • 192. Ex1: Guesser Game. The use enters a number between 1 and 4. If the guessed number is the same as the computer randomly generated number between 1 and 4 the Guesser wins package MyJavaLab; import java.util.*; public class Guesser { public static void main(String[]args) { Scanner input = new Scanner(System.in); Random rand = new Random(); System.out.println("WELCOME TO THE GUESSING GAME"); System.out.println("PICK ANY NUMBER FROM 1 TO 4"); System.out.print("ENTER YOUR NUMBER >> "); // this is where your number is inputed int number = input.nextInt(); //this is where your computer inputs its value //The random number generated with 4 as argument //always fall between 0 and 3. So, 1 must be added //because we don't want to enter 0, but 4 is a possible input. int randnumb = 1 + rand.nextInt(4); if (number == randnumb) { System.out.println("YOU WIN O !!! "); } else { System.out.println("TRY AGAIN "); System.out.println("COMPUTER ENTERED " + randnumb); } } }
  • 193. EX2: This class ScoreGrader.java receives students scores and grade them according to their classes as the application output.
  • 194. package MyJavaLab; import java.util.*; public class ScoreGrader { public static void main(String[]args) { Scanner input = new Scanner(System.in); System.out.println("Enter your Score "); int score = input.nextInt(); if(score >= 70 && score <=100) { System.out.println("FIRST CLASS A++"); } else if(score >= 60 && score <= 69) { System.out.println("SECOND CLASS B++"); } else if(score >= 50 && score <= 59) { System.out.println("SECOND CLASS C"); } else if(score >= 45 && score <= 49) { System.out.println("THIRD CLASS D"); } else if(score >= 44 && score <= 36) { System.out.println("PASS E"); } else if(score >= 0 && score <= 35) {
  • 196. EX3: This class, Randomizer.java generates a series of random numbers (from 1 to 6) a hundred times, count the frequency for which each of the numbers from 1 to 6 occurs and display the result of the frequency of occurence by the particular number in the output. package MyJavaLab; import java.util.*; public class Randomizer { public static void main(String []args) { int frqOne = 0; int frqTwo = 0; int frqThree = 0 ; int frqFour = 0; int frqFive = 0; int frqSix = 0; Random rand = new Random(); for (int i = 0; i <= 100; i++) { int number = 1+ rand.nextInt(6); System.out.print(number + ""); switch (number) { case 1: frqOne++; break; case 2: frqTwo++;
  • 197. break; case 3: frqThree++; break; case 4: frqFour++; break; case 5: frqFive++; break; case 6: frqSix++; break; } } System.out.println(""); System.out.println("Number 1 was generated "+frqOne+" times"); System.out.println("Number 2 was generated "+frqTwo+" times"); System.out.println("Number 3 was generated "+frqThree+" times"); System.out.println("Number 4 was generated "+frqFour+" times"); System.out.println("Number 5 was generated "+frqFive+" times"); System.out.println("Number 6 was generated "+frqSix+" times"); } }
  • 198. EX4: Number Guess Game. package gnumber; import java.util.Random; import java.util.Scanner; public class GNumber { public static void main(String[] args) { int computerNumber; int yourGuess; Random myRandom = new Random(); Scanner myScanner = new Scanner(System.in); //get the computer's number between 1 and 10 computerNumber = 1 + myRandom.nextInt(10); System.out.println("I'm thinking of a number between 1 and 10 "); //get your guess System.out.print("What do you think it is? "); yourGuess = myScanner.nextInt(); //analyze guess and get results if(yourGuess == computerNumber) // you got it { System.out.println("You got it! That's my number!"); } else if(yourGuess < computerNumber) //too low { System.out.println("You sre too low! My number was " + computerNumber); } else //too high { System.out.println("You are too high! My number was " + computerNumber); } } }
  • 199. Modified Number Guess Game package newguess; import java.util.Random; import java.util.Scanner; public class NewGuess { public static void main(String[] args) { int computerNumber; int yourGuess; Random myRandom = new Random(); Scanner myScanner = new Scanner(System.in); //get the computer's number between 1 and 10 computerNumber = 1 + myRandom.nextInt(10); System.out.println("I'm thinking of a number between 1 and 10"); do { //get your guess System.out.print("What do you think it is? "); yourGuess = myScanner.nextInt(); //analyze guess and get results if(yourGuess == computerNumber) // you got it { System.out.println("You got it! That's my number! "); } else if(yourGuess < computerNumber) //too low { System.out.println("You sre too low! "); } else //too high { System.out.println("You are too high! " ); } }
  • 200. while(yourGuess != computerNumber); } } Number Guess Game (Modified to count the number of guess before the correct answer) package newguess; import java.util.Random; import java.util.Scanner; public class NewGuess { public static void main(String[] args) { int computerNumber; int yourGuess; int count = 0; // used to count the number of guesses made. Random myRandom = new Random(); Scanner myScanner = new Scanner(System.in); //get the computer's number between 1 and 10 computerNumber = 1 + myRandom.nextInt(10); System.out.println("I'm thinking of a number between 1 and 10"); do {
  • 201. //get your guess System.out.print("What do you think it is? "); yourGuess = myScanner.nextInt(); //analyze guess and get results if(yourGuess == computerNumber) // you got it { System.out.println("nYou got it! That's my number! "); count = count + 1; } else if(yourGuess < computerNumber) //too low { System.out.println("nYou sre too low! "); count = count + 1; } else //too high { System.out.println("nYou are too high! " ); count = count + 1; } System.out.println("nYou made " + count + " guesses "); } while(yourGuess!=computerNumber); } }
  • 202. EX5: Code for generating a set of randomly generated numbers: Note that this code is intwo parts – the second part being the method that generates the random numbers //First Part package shuffle; import java.util.Random; public class Shuffle { public static void main(String[] args) { //declare needed array int[] myIntegers = new int[10]; //shuffle integers from 0 to 9 myIntegers = nIntegers(10); //print out results for(int i = 0; i < 10; i++) { System.out.println("Value is " + myIntegers[i]); } } //This code returns n randomly sorted integers public static int[] nIntegers(int n) { /* * Returns n randomly sorted integers 0 to n - 1 */ int nArray[] = new int[n]; int temp, s; Random myRandom = new Random(); // initialize array from 0 to n - 1 for (int i = 0; i < n; i++) { nArray[i] = i; } // perform one-card shuffle // i is number of items remaining in list // s is the random selection from that list // we swap last item i – 1 with selection s for (int i = n; i >= 1; i--) { s = myRandom.nextInt(i); temp = nArray[s]; nArray[s] = nArray[i - 1]; nArray[i - 1] = temp; } return(nArray); } }
  • 204. EX 6: This code displays the elapsed time – Stopwatch counts in milliseconds package stopwatch; import java.util.Scanner; public class Stopwatch { public static void main(String[] args) { Scanner myScanner = new Scanner(System.in); long startTime; String stopIt = ""; while (!stopIt.equals("0")) { System.out.print("nPress <Enter> to start stopwatch. "); myScanner.nextLine(); System.out.println("Stopwatch is running ..."); startTime = System.currentTimeMillis(); System.out.print("Press <Enter> to stop stopwatch (enter a 0 to stop the program)."); stopIt = myScanner.nextLine(); System.out.println("Elapsed time is " + (System.currentTimeMillis() - startTime) / 1000.0 + " seconds."); } } }
  • 205. EX7: Rolling Dice: This project draws 2 dicee and sums the numbers displayed. The numbers displayed are showed on the die as graphics. package dice; import java.util.Scanner; import java.util.Random; public class Dice { public static void main(String[] args) { Scanner myScanner = new Scanner(System.in); int die1; int die2; Random myRandom = new Random(); String stopIt = ""; do { System.out.println("nDice are rolling ..."); die1 = myRandom.nextInt(6) + 1; drawDie(die1); die2 = myRandom.nextInt(6) + 1; drawDie(die2); System.out.println("nTotal is: " + (die1 + die2)); System.out.print("Press <Enter> to roll again, enter a 0 to stop: "); stopIt = myScanner.nextLine(); } while (!stopIt.equals("0")); } public static void drawDie(int n) { // use character graphics to draw dice System.out.println("n-----"); switch (n) { case 1: // draw a die with one spot System.out.println("| |"); System.out.println("| * |"); System.out.println("| |"); break; case 2: // draw a die with two spots System.out.println("|* |"); System.out.println("| |"); System.out.println("| *|"); break; case 3: // draw a die with three spots System.out.println("|* |");
  • 206. System.out.println("| * |"); System.out.println("| *|"); break; case 4: // draw a die with four spots System.out.println("|* *|"); System.out.println("| |"); System.out.println("|* *|"); break; case 5: // draw a die with five spots System.out.println("|* *|"); System.out.println("| * |"); System.out.println("|* *|"); break; case 6: // draw a die with six spots System.out.println("|* *|"); System.out.println("|* *|"); System.out.println("|* *|"); break; } System.out.println("-----"); } }
  • 207. EX8: This code display the states and their respective capital cities (US). The states are randomly selected and 4 randomly selected capital cities are displayed for the user to select the correct city. package statecapitals; import java.util.Scanner; import java.util.Random; public class StateCapitals { public static void main(String[] args) { Scanner myScanner = new Scanner(System.in); Random myRandom = new Random(); int answer; int capitalSelected = 0; String[] state = new String[50]; String[] capital = new String[50]; int[] listedCapital = new int[4]; int[] capitalUsed = new int[50]; // initialize arrays state[0] = "Alabama" ; capital[0] = "Montgomery"; state[1] = "Alaska" ; capital[1] = "Juneau"; state[2] = "Arizona" ; capital[2] = "Phoenix"; state[3] = "Arkansas" ; capital[3] = "Little Rock"; state[4] = "California" ; capital[4] = "Sacramento"; state[5] = "Colorado" ; capital[5] = "Denver"; state[6] = "Connecticut" ; capital[6] = "Hartford"; state[7] = "Delaware" ; capital[7] = "Dover"; state[8] = "Florida" ; capital[8] = "Tallahassee"; state[9] = "Georgia" ; capital[9] = "Atlanta"; state[10] = "Hawaii" ; capital[10] = "Honolulu"; state[11] = "Idaho" ; capital[11] = "Boise"; state[12] = "Illinois" ; capital[12] = "Springfield"; state[13] = "Indiana" ; capital[13] = "Indianapolis"; state[14] = "Iowa" ; capital[14] = "Des Moines"; state[15] = "Kansas" ; capital[15] = "Topeka"; state[16] = "Kentucky" ; capital[16] = "Frankfort"; state[17] = "Louisiana" ; capital[17] = "Baton Rouge"; state[18] = "Maine" ; capital[18] = "Augusta"; state[19] = "Maryland" ; capital[19] = "Annapolis"; state[20] = "Massachusetts" ; capital[20] = "Boston"; state[21] = "Michigan" ; capital[21] = "Lansing"; state[22] = "Minnesota" ; capital[22] = "Saint Paul"; state[23] = "Mississippi" ; capital[23] = "Jackson"; state[24] = "Missouri" ; capital[24] = "Jefferson City"; state[25] = "Montana" ; capital[25] = "Helena"; state[26] = "Nebraska" ; capital[26] = "Lincoln"; state[27] = "Nevada" ; capital[27] = "Carson City"; state[28] = "New Hampshire" ; capital[28] = "Concord";
  • 208. state[29] = "New Jersey" ; capital[29] = "Trenton"; state[30] = "New Mexico" ; capital[30] = "Santa Fe"; state[31] = "New York" ; capital[31] = "Albany"; state[32] = "North Carolina" ; capital[32] = "Raleigh"; state[33] = "North Dakota" ; capital[33] = "Bismarck"; state[34] = "Ohio" ; capital[34] = "Columbus"; state[35] = "Oklahoma" ; capital[35] = "Oklahoma City"; state[36] = "Oregon" ; capital[36] = "Salem"; state[37] = "Pennsylvania" ; capital[37] = "Harrisburg"; state[38] = "Rhode Island" ; capital[38] = "Providence"; state[39] = "South Carolina" ; capital[39] = "Columbia"; state[40] = "South Dakota" ; capital[40] = "Pierre"; state[41] = "Tennessee" ; capital[41] = "Nashville"; state[42] = "Texas" ; capital[42] = "Austin"; state[43] = "Utah" ; capital[43] = "Salt Lake City"; state[44] = "Vermont" ; capital[44] = "Montpelier"; state[45] = "Virginia" ; capital[45] = "Richmond"; state[46] = "Washington" ; capital[46] = "Olympia"; state[47] = "West Virginia" ; capital[47] = "Charleston"; state[48] = "Wisconsin" ; capital[48] = "Madison"; state[49] = "Wyoming" ; capital[49] = "Cheyenne"; // begin questioning loop do { // Generate the next question at random answer = myRandom.nextInt(50); // Display selected state System.out.println("nState is: " + state[answer] + "n"); // capitalUsed array is used to see which state capitals have //been selected as possible answers for (int i = 0; i < 50; i++) { capitalUsed[i] = 0; } // Pick four different state indices (J) at random // These are used to set up multiple choice answers // Stored in the listedCapital array for (int i = 0; i < 4; i++) { //Find value not used yet and not the answer int j; do { j = myRandom.nextInt(50); } while (capitalUsed[j] != 0 || j == answer); capitalUsed[j] = 1; listedCapital[i] = j; }
  • 209. // Now replace one item (at random) with correct answer listedCapital[myRandom.nextInt(4)] = answer; // Display multiple choice answers for (int i = 0; i < 4; i++) { System.out.println((i + 1) + " - " + capital[listedCapital[i]]); } System.out.print("nWhat is the Capital? (Enter 0 to Stop) "); capitalSelected = myScanner.nextInt(); // check answer if (capitalSelected != 0) { if (listedCapital[capitalSelected - 1] == answer) { System.out.println("That's it ... good job!"); } else { System.out.println("Sorry, the answer is " + capital[answer] +"."); } } } while (capitalSelected != 0); } }
  • 210. EX 9: This code calculate the total amount with weekly deposits and stated annual interest rate. NOTE: This worked examples also have severalexplanation. Read through the comments to see the example of how to use the .nextLine() method if it is preceeded by an int or Double variable; package savings; import java.util.Scanner; public class Savings { public static void main(String[] args) { //declare and initialize variables; String yourName; double deposit = 0.0; double rate =0.0; //annual interest rate expressed as double int weeks = 0; double total = 0.0; double totalR = 0.0; Scanner myScanner = new Scanner(System.in); //ask for user name System.out.println("Hello, what's your name? "); yourName = myScanner.nextLine(); // get deposit amount System.out.println("nHow much will you deposit each week? "); deposit = myScanner.nextDouble(); //get number of weeks System.out.println("For how many weeks? "); weeks = myScanner.nextInt(); //what's the interest rate System.out.println("Enter the interest rate "); rate = myScanner.nextDouble(); //compute and display total if(rate <= 0.0) { total = deposit * weeks; System.out.print("n" + yourName + ", after " + weeks + " weeks, you will have $" + total + ", in your savings.n"); } else {
  • 211. total = (deposit * (Math.pow((1 + rate / 5200), weeks) - 1) / rate) * 5200; System.out.print("n" + yourName + ", after " + weeks + " weeks, you will have $" + total + ", in your savings.n"); } } } With deposit = 10, weeks = 20, interest rate = 6.5. With deposit = 10, weeks = 20, interest rate = 0.0;
  • 212. EX10: Using Java to do a simulation program: A very powerful use of computers is to do something called simulation. Before building an actual airplane, companies “build” the plane on a computer and simulate its performance. This is much cheaper and far safer than testing actual airplanes. Engineers simulate how a building might react to an earthquake to help them design better buildings. And, businesses use computers to simulate how decisions could affect their profits. Based on computer results, they decide how and where to invest their money. In this project, we will build a small business simulation. We will simulate the operation of the neighborhood kids’ backyard lemonade stand. Based on the temperature, they set a selling price for their lemonade (the hotter it is, the more they can charge). They will then be told how many cups were sold and how much money was made. If the kids are too greedy, asking too much for their product, they won’t sell as much. If they’re too nice, they won’t make as much money. It’s a tough world out there! This project is saved as Lemonade. Source: Beginning Java - Philip Conrod & Lou Tylee ©2015 Kidware Software LLC www.kidwaresoftware.com, page 130 Project Design You’ll sell lemonade for five days (simulated days). On each day, you will be told the temperature. Based on this temperature, you set a price for your lemonade. You will be told how many cups of lemonade you sold and how much money you made. The steps to follow on each day: 1. Computer picks a random temperature. 2. You assign a price for each cup of lemonade. 3. Computer analyzes the information and computes number of cups sold. 4. Your sales are computed and displayed. The first step is a straightforward use of the random number object. In the second step, we will use the Scanner nextDouble method to get the price. Step 3 is the difficult one – how does the computer determine cups sold? In this project, we will give you the code to do this (code we made up) in the form of a method you can use. This is something done all the time in programming – borrowing and using someone else’s code. In this method, you provide the temperature and the price (the arguments) and the method returns the number of cups sold. Finally, the println method will be used to output the results of each day’s sales. Let me try to explain what I’m doing here. First, I assume there is a bestPrice (most you can charge) for a cup of lemonade, based on the temperature (t). You can charge more on hotter days. The equation used assumes this bestPrice ranges from 20 cents at 60 degrees to a random value between 45 and 65 cents at 100 degrees. Similarly, there is a maximum number of cups you can sell (maxSales) based on temperature. You can sell more on hotter days.
  • 213. The equation used assumes maxSales ranges from 20 cups at 60 degrees to a random value between 150 and 250 at 100 degrees. Before returning a number of cups, I compute an adjustment variable. This is used to adjust your sales based on your input price. If you ask more than the bestPrice, sales will suffer because people will think you are asking too much for your product. Your sales will also suffer if you charge too little for lemonade! Why’s that? Many people think if something doesn’t cost enough, it may not be very good. You just can’t win in the business world. So, adjustment is computed based on how far your set price (p) is from the bestPrice. Once adjustment is found, it is multiplied times the maxSales and returned to the calling program in this line of code: return((int) (adjustment * maxSales)); Notice you see something you have never seen before, the words int in parentheses before the product. This is called a casting in Java and converts the product (adjustment * maxSales), a double value, to the required int return value for the number of cups sold. You can’t sell a fraction of a cup! This brings up a good point. Many times, when using someone else’s Java code, you may see things you don’t recognize. What do you do? The best thing is to consult some Java reference (another Java programmer, a textbook, the Java website) and do a little research and self-study. This helps you learn more and helps you become a better Java programmer. Notice if you play this program as a game, you wouldn’t know all the details behind the rules (how cupSales are computed). You would learn these rules as you play. That’s what happens in all computer games – the games have rules and, after many plays, you learn what rules the programmers have included. If you can’t follow all the math in the getSales method, that’s okay. You don’t really need to – just trust that it does the job. Actually, Java programmers use methods all the time without an understanding of how they work (do you know how Java finds the square root of a number?). In such cases, we rely on the method writer to tell us what information is required (arguments) and what information is computed (returned value) and trust that the method works. That’s the beauty of methods – we get code without doing the work. Below is the complete code: package lemonade; import java.util.Random; import java.util.Scanner; public class Lemonade { public static void main(String[] args) { // define variables int dayNumber;
  • 214. int temperature; int cupPrice; int cupsSold; double daySales; double totalSales; Random myRandom = new Random(); Scanner myScanner = new Scanner(System.in); // start loop of five days dayNumber = 1; totalSales = 0.0; do { // pick a random temperature between 60 and 100 temperature = myRandom.nextInt(41) + 60; System.out.println("nWelcome to Day " + dayNumber + ", the temperature is " + temperature + " degrees."); // get price System.out.print("How many cents do you want to charge for a cup of lemonade? "); cupPrice = myScanner.nextInt(); // get cups sold, provide sales report cupsSold = getSales(temperature, cupPrice); daySales = cupsSold * cupPrice / 100.0; totalSales = totalSales + daySales; System.out.println("nYou sold " + cupsSold + " cups of lemonade, earning $" + daySales + "."); if (dayNumber > 1) { System.out.println("Total sales after " + dayNumber + " days are $" + totalSales + "."); } // go to next day dayNumber = dayNumber + 1; } while (dayNumber < 6); System.out.println("nThe lemonade stand is now closed."); } / * * getSales method * input temperature t and price p * output number of cups sold * KIDware */ public static int getSales(int t, double p) { // t represents temperature // p represents price double bestPrice;
  • 215. double maxSales; double adjustment; Random anotherRandom = new Random(); // find best price bestPrice = (t - 60.0) * (45 - anotherRandom.nextInt(20)) / 40.0 + 20.0; // find maximum sales maxSales = (t - 60.0) * (230 -anotherRandom.nextInt(100)) / 40.0 + 20.0; // find sales adjustment adjustment = 1.0 - Math.abs((p - bestPrice) / bestPrice); if (adjustment < 0.0) { adjustment = 0.0; } // return adjusted sales return((int) (adjustment * maxSales)); } }
  • 217. EX11. This method creates a “shuffled” array of 10 random numbers. Shuffling routine using nIntegers() method package shuffle; import java.util.Random; public class Shuffle /* This code creates an array of length 10. This array is then filled with the random integers 0 to 9 by calling the nIntegers method. The results are printed using 10 calls to println in the for loop. */ { public static void main(String[] args) { //declare needed array int[] myIntegers = new int[10]; //shuffle integers from 0 to 9 myIntegers = nIntegers(10); //print out results for(int i = 0; i < 10; i++) { System.out.println("Value is " + myIntegers[i]); } } /* // Note: This is the nIntegers() method, it generates random integers from 0 to 9 */ public static int[] nIntegers(int n) { /* * Returns n randomly sorted integers 0 to n - 1 */ int nArray[] = new int[n]; int temp, s; Random myRandom = new Random(); // initialize array from 0 to n - 1 for (int i = 0; i < n; i++) { nArray[i] = i; } // perform one-card shuffle // i is number of items remaining in list // s is the random selection from that list // we swap last item i – 1 with selection s for (int i = n; i >= 1; i--) { s = myRandom.nextInt(i); temp = nArray[s]; nArray[s] = nArray[i - 1];
  • 218. nArray[i - 1] = temp; } return(nArray);}}
  • 220. EX12: Card Wars In this project, we create a simplified version of the kid’s card game - War. You play against the computer. You each get half a deck of cards (26 cards). Each player turns over one card at a time. The one with the higher card wins the other player’s card. The one with the most cards at the end wins. We can use our shuffle routine to shuffle the deck of cards (compute 52 random integers from 0 to 51). Describing the handed-out cards requires converting the integer card value to an actual card in the deck (value and suit). We will create a Java method to do this. Comparing the cards is relatively easy (we’ll add the capability to our card display method), as is updating and displaying the scores (we will use our old friend, the println method). No input is ever needed from the user (besides pressing a key on the keyboard to see the cards) – he/she merely watches the results go by. Project Development Before building the project, let’s do a little “up front” work. In the Project Design, we see a need for a method that, given a card number (0 to 51), (1) determines and displays which card (suit, value) in a deck it represents, and (2) determines its corresponding numerical value to allow comparisons. We will create this method now. Displaying a card consists of answering two questions: what is the card suit and what is the card value? The four suits are hearts, diamonds, clubs, and spades. The thirteen card values, from lowest to highest, are: Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten, Jack, Queen, King, Ace. We’ve seen in our shuffle routine that a card number will range from 0 to 51. How do we translate that card number to a card suit and value? (Notice the distinction between card number and card value - card number ranges from 0 to 51, card value can only range from Two to Ace.) We need to develop some type of translation rule. This is done all the time in Java. If the number you compute with or work with does not directly translate to information you need, you need to make up rules to do the translation. For example, the numbers 1 to 12 are used to represent the months of the year. But, these numbers tell us nothing about the names of the month. We need a rule to translate each number to a month name. We know we need 13 of each card suit. Hence, an easy rule to decide suit is: cards numbered 0 - 12 are hearts, cards numbered 13 - 25 are diamonds, cards numbered 26 - 38 are clubs, and cards numbered 39 - 51 are spades. For card values, lower numbers should represent lower cards. A rule that does this for each number in each card suit is:
  • 221. As examples, notice card 22 is a Jack of Diamonds. Card 30 is a Six of Clubs. We now have the ability to describe a card. How do we compare them? Card comparisons must be based on a numerical value, not displayed card value -it’s difficult to check if King is greater than Seven, though it can be done. So, one last rule is needed to relate card value to numerical value. It’s a simple one - start with a Two having a numerical value of 0 (lowest) and go up, with an Ace having a numerical value of 12 (highest). This makes numerical card comparisons easy. Notice hearts card numbers already go from 0 to 12. If we subtract 13 from diamonds numbers, 26 from clubs numbers, and 39 from spades numbers, each of those card numbers will also range from 0 to 12. This gives a common basis for comparing cards. This all may seem complicated, but look at the Java code and you’ll see it really isn’t. The Java method (cardDisplay) that takes the card number (n) as an input and returns its numeric value (0 to 12) to allow comparisons. The method also prints a string description (value and suit) of the corresponding card, using the above table for translation. public static int cardDisplay(int n) { // given card number n (0 - 51), prints description // and returns numeric value String suit; String[] value = new String[13]; value[0] = "Two"; value[1] = "Three"; value[2] = "Four"; value[3] = "Five";
  • 222. value[4] = "Six"; value[5] = "Seven"; value[6] = "Eight"; value[7] = "Nine"; value[8] = "Ten"; value[9] = "Jack"; value[10] = "Queen"; value[11] = "King"; value[12] = "Ace"; // determine your card's suit, adjust numeric value n if (n >= 0 && n <= 12) { suit = "Hearts"; } else if (n >= 13 && n <= 25) { suit = "Diamonds"; n = n - 13; } else if (n >= 26 && n <= 38) { suit = "Clubs"; n = n - 26; } else { suit = "Spades"; n = n - 39; } // print description System.out.println(value[n] + " of " + suit); // return numeric value return(n); } You should be able to see how this works. With this method built, we can use it to create the complete Card Wars project. The following are the complete codes for the CardWars project: /*The Game Concept is as follows: 1. Shuffle a deck of cards. 2. Computer gives itself a card and player a card. 3. Computer compares cards, the player with the higher card wins both cards. 4. Scores are computed and displayed. 5. Process continues until all cards have been dealt from the deck. */ package cardwars; import java.util.Random;
  • 223. import java.util.Scanner; public class CardWars { public static void main(String[] args) { // declare needed variables in main method int cardIndex = 0; int computerScore = 0; int yourScore = 0; int computerCard; int yourCard; int[] myCards = new int[52]; Scanner myScanner = new Scanner(System.in); // shuffle the cards myCards = nIntegers(52); // do loop starting the game do { // display computer card, then your card. This code picks and displays the cards System.out.print("My card: "); computerCard = cardDisplay(myCards[cardIndex]); System.out.print("Your card: "); yourCard = cardDisplay(myCards[cardIndex + 1]); // see who won (or if there is a tie) and compute the scores if (yourCard > computerCard) { System.out.println("You win!"); yourScore = yourScore + 2; } else if (computerCard > yourCard) { System.out.println("I win!"); computerScore = computerScore + 2; } else { System.out.println("It's a tie."); yourScore = yourScore + 1; computerScore = computerScore + 1; } //Next we print the results: System.out.println("My Score: " + computerScore); System.out.println("Your Score: " + yourScore); cardIndex = cardIndex + 2; System.out.print("There are " + (52 - cardIndex) + " cards remaining. "); System.out.println("Press any key."); myScanner.nextLine(); }
  • 224. while ((52 - cardIndex) > 0); System.out.println("Game over."); } //Card Display: This is the method that display a randomly selected card public static int cardDisplay(int n) { // given card number n (0 - 51), prints description and returns numeric value String suit; String[] value = new String[13]; value[0] = "Two"; value[1] = "Three"; value[2] = "Four"; value[3] = "Five"; value[4] = "Six"; value[5] = "Seven"; value[6] = "Eight"; value[7] = "Nine"; value[8] = "Ten"; value[9] = "Jack"; value[10] = "Queen"; value[11] = "King"; value[12] = "Ace"; // determine your card's suit, adjust numeric value n if (n >= 0 && n <= 12) { suit = "Hearts"; } else if (n >= 13 && n <= 25) { suit = "Diamonds"; n = n - 13; } else if (n >= 26 && n <= 38) { suit = "Clubs"; n = n - 26; } else { suit = "Spades"; n = n - 39; } // print description System.out.println(value[n] + " of " + suit); // return numeric value
  • 225. return(n); } // This is the Shuffle Method. It returns n randomly sorted integers from 0 to n - 1 public static int[] nIntegers(int n) { // Returns n randomly sorted integers from 0 to n - 1 int nArray[] = new int[n]; int temp, s; Random myRandom = new Random(); // initialize array from 0 to n - 1 for (int i = 0; i < n; i++) { nArray[i] = i; } // perform one-card shuffle // i is number of items remaining in list // s is the random selection from that list // we swap last item i - 1 with selection s for (int i = n; i >= 1; i--) { s = myRandom.nextInt(i); temp = nArray[s]; nArray[s] = nArray[i - 1]; nArray[i - 1] = temp; } return(nArray); } }
  • 227. EX13: Units Converter class: - This class converts length from one unit of measure (inch, foot, yard, mile, centimeter, meter, kilometer) to another. The idea of the program is simple. Type a value and choose its units. Display that value converted to several other units. Note how the conversion factors are stored in a two-dimensional array (table). package converter; import java.util.Scanner; public class Converter { public static void main(String[] args) { //Declare Variables Scanner myScanner = new Scanner(System.in); String[] units = new String[7]; double[][] conversions = new double[7][7]; double fromValue; int fromUnits; /* Establish conversion factors - stored in a 2 - dimensional array or table = the first number is the table row, the second number is the table column. */ conversions[0][0] = 1.0; //inches to inches conversions[0][1] = 1.0/12.0; //inches to feet conversions[0][2] = 1.0/36.0; //inches to yard conversions[0][3] = (1.0/12)/5280.0; //inches to mile conversions[0][4] = 2.54; // inches to cm conversions[0][5] = 2.54/100; //inches to km conversions[0][6] = 2.54/100000; //inches to km for (int i = 0; i<7; i++) { conversions[1][i] = 12.0 * conversions[0][i]; conversions[2][i] = 36.0 * conversions[0][i]; conversions[3][i] = 5280.0 *(12.0 * conversions[0][i]); conversions[4][i] = conversions[0][i] / 2.54; conversions[5][i] = 100.0 * conversions[0][i] / 2.54; conversions[6][i] = 100000.0 * (conversions[0][i] /2.54); }
  • 228. //initialize variables units[0] = "inches (in)"; units[1] = "feet (ft) "; units[2] = "yards (yd) "; units[3] = "miles (mi)"; units[4] = "centimeters (cm)"; units[0] = "metres (m)"; units[0] = "kilometers (km)"; //trick Java into continuing loop while(1 != 2) { System.out.print("nEnter a value to convert (Enter 0 to stop): "); fromValue = myScanner.nextDouble(); if (fromValue == 0) { break; } for (int i = 0; i < 7; i++) { System.out.println(i + 1 + " - " + units[i]); } do { System.out.println("What unit is the value in? "); fromUnits = myScanner.nextInt(); } while (fromUnits < 1 || fromUnits > 7); // arrays are zero-based, so subtract 1 fromUnits = fromUnits -1; // Do unit conversion System.out.println("n" + fromValue + " " + units[fromUnits] + " is:n"); for (int i = 0; i < 7; i++) { System.out.println(fromValue * conversions[fromUnits][i] + " " + units[i]); } } } }
  • 230. EX14: Multiplication Table: This program generates 2 random numbers from 1 to 12 and ask you to find the product. Giving the answer for wrong responses and calculating the percentage of correct answers at the end. package timestables; import java.util.Random; import java.util.Scanner; public class TimesTables { public static void main(String[] args) { Scanner myScanner = new Scanner(System.in); //Variables declaraton int number1, number2; int product; int yourAnswer; int numProb; int numRight; Random myRandom = new Random(); numProb = 0; numRight = 0; //display the problem for(int i = 1; i < 13; i++) { numProb = numProb + 1; //Generate Random numbers for factors number1 = myRandom.nextInt(13); number2 = myRandom.nextInt(13); // find product product = number1 * number2; System.out.println("nProblem " + numProb + " : "); System.out.print("What is " + number1 + " X " + number2 + " = ") ; yourAnswer = myScanner.nextInt(); //Check answer and update score if(yourAnswer == product) { numRight = numRight + 1; System.out.println("That's correct!"); } else { System.out.println("Answer is " + product); }
  • 231. System.out.println("Score: " + 100.0*numRight/numProb + "%"); } } }
  • 232. EX15 Loan Repayment Calculator: Given a loan amount, annual interest rate and the number of months for repayment. package loan; import java.util.Scanner; public class Loan { public static void main(String[] args) { //this next line just ricks Java to keep the loop going while (1 != 2) { Scanner myScanner = new Scanner(System.in); //declare variables double loan; double interest; int months; double payment; double multiplier; //input values System.out.println("Enter loan amount (Enter 0 to stop): "); loan = myScanner.nextDouble(); System.out.println("Enter yearly interest rate: "); interest = myScanner.nextDouble(); System.out.println("Enter number of months to pay back the loan; "); months = myScanner.nextInt(); //compute interest multiplier multiplier = Math.pow((1 + interest/1200), months); //compute payment payment = loan * interest * multiplier / (1200 * (multiplier - 1)); System.out.println("Your monthly payment in $" + payment + "n"); } } }
  • 233. EX16: Portfolio Value /* * In this project, we will build a tool that lets you determine the current value * of your stock holdings. You store when you bought a particular stock, how * many shares you bought and how much you paid. Then, whenever you want, * you enter current values to determine your gain (or possible losses). * * In this program, you need to store information about your stocks (date purchased, * purchase price and shares owned) in arrays. When the program runs, you select * a stock. Then, you type in the current price and you will be shown the current * value and yearly return for that stock. Notice how we limit the choice of stock * number and how all the dates are formatted and used. */ package portfolio; import java.util.Date; import java.text.DateFormat; import java.util.Scanner; public class Portfolio { public static void main(String[] args) { Scanner myScanner = new Scanner(System.in); // declare variables int numberStocks; int currentStock; double currentPrice; double currentValue; double currentReturn; String[] stockDate = new String[25]; String[] stockName = new String[25]; double[] stockPrice= new double[25]; int[] stockShares = new int[25]; Date today = new Date(); Date display = new Date(); // Set Stock Information numberStocks = 5; stockDate[0] = "5/1/00" ; stockName[0] = "Accellup"; stockPrice[0] = 30 ; stockShares[0] = 200;
  • 234. stockDate[1] = "2/1/99" ; stockName[1] = "Guaranty"; stockPrice[1] = 10 ; stockShares[1] = 100; stockDate[2] = "3/1/99" ; stockName[2] = "Diamond Bank"; stockPrice[2] = 20 ; stockShares[2] = 300; stockDate[3] = "4/1/99" ; stockName[3] = "Dangote Flour"; stockPrice[3] = 15 ; stockShares[3] = 200; stockDate[4] = "4/10/02" ; stockName[4] = "Halliburton"; stockPrice[4] = 40 ; stockShares[4] = 400; System.out.println("nToday is: " + DateFormat.getDateInstance(DateFormat.FULL).format(today)); // trick Java into repeating loop while (1 != 2) { System.out.println("nYour Stocks:"); for (int i = 0; i < numberStocks; i++) { System.out.println(i + 1 + " - " + stockName[i]); } do { System.out.print("nPick a stock (Or Enter 0 to STOP) "); currentStock = myScanner.nextInt(); } while (currentStock < 0 || currentStock > numberStocks); if (currentStock == 0) { break; } currentStock = currentStock - 1; System.out.println("nStock: " + stockName[currentStock]); // convert string date to Date class for display try { display = DateFormat.getDateInstance(DateFormat.SHORT).parse(stockDate[currentSt ock]); } catch(java.text.ParseException e) { System.out.println("Error parsing date" + e); } System.out.println("Date Purchased: " + DateFormat.getDateInstance(DateFormat.FULL).format(display));
  • 235. System.out.println("Purchase Price: $" + stockPrice[currentStock]); System.out.println("Shares Held: " + stockShares[currentStock]); System.out.println("Initial Value: $" + stockPrice[currentStock] * stockShares[currentStock]); System.out.print("What is current selling price? "); currentPrice = myScanner.nextDouble(); // compute todays value and percent return currentValue = currentPrice * stockShares[currentStock]; System.out.println("Current Value: $" + currentPrice * stockShares[currentStock]); // Daily increase long diffDays = (today.getTime() - display.getTime()) / (24 * 60 * 60 * 1000); currentReturn = (currentValue / (stockPrice[currentStock] * stockShares[currentStock]) - 1) / diffDays; // Yearly return currentReturn = 100 * (365 * currentReturn); System.out.println("Yearly return: " + currentReturn + "%"); } } }
  • 237. EX17: Demonstrating typical steps for creating a GUI app 1. The JStopwatch application 2. The GridBag layout for setting control positions 3. The steps taken:  Declare and create the control (class level scope): ControlType controlName = new ControlType();  Position the control: gridConstraints.gridx = desiredColumn; gridConstraints.gridy = desiredRow; getContentPane().add(controlName, gridConstraints); (assumes a gridConstraints object has been created).  Add the control listener: controlName.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { controlNameActionPerformed(e); } });  Write the control event method: private void controlNameActionPerformed(ActionEvent e) { [Java code to execute] }
  • 238. 4. JStopwatch.java class package jstopwatch; import javax.swing.*; import java.awt.*; import java.awt.event.*; public class JStopwatch extends JFrame { // declare controls used JButton startButton = new JButton(); JButton stopButton = new JButton(); JButton exitButton = new JButton(); JLabel startLabel = new JLabel(); JLabel stopLabel = new JLabel(); JLabel elapsedLabel = new JLabel();; JTextField startTextField = new JTextField(); JTextField stopTextField = new JTextField(); JTextField elapsedTextField = new JTextField(); // declare class level variables long startTime; long stopTime; double elapsedTime; //next is the main method public static void main(String args[]) { new JStopwatch().show(); }
  • 239. // frame constructor. This constructor is used for creating the //JStopwatch frame public JStopwatch() { setTitle("Stopwatch Application"); //code for exiting the form (class) addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { exitForm(e); } }); //declares the type of form layout used – GridBag in this case getContentPane().setLayout(new GridBagLayout()); // Add controls, each in their respective grid x, y //coordinates GridBagConstraints gridConstraints = new GridBagConstraints(); startButton.setText("Start Timing"); //start timing button gridConstraints.gridx = 0; gridConstraints.gridy = 0; getContentPane().add(startButton, gridConstraints); //adds action listener for Start Timing event startButton.addActionListener(new ActionListener() {
  • 240. public void actionPerformed(ActionEvent e) { startButtonActionPerformed(e); } }); //Stop button added into grid position stopButton.setText("Stop Timing"); gridConstraints.gridx = 0; gridConstraints.gridy = 1; getContentPane().add(stopButton, gridConstraints); //adds ActionListener for Stop timing event stopButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { stopButtonActionPerformed(e); } }); //adds Exit button added into grid position exitButton.setText("Exit"); gridConstraints.gridx = 0; gridConstraints.gridy = 2; getContentPane().add(exitButton, gridConstraints); //adds action listener for Exit button – closing the application exitButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e)
  • 241. { exitButtonActionPerformed(e); } }); startLabel.setText("Start Time"); //label gridConstraints.gridx = 1; gridConstraints.gridy = 0; getContentPane().add(startLabel, new GridBagConstraints()); stopLabel.setText("Stop Time"); //label gridConstraints.gridx = 1; gridConstraints.gridy = 1; getContentPane().add(stopLabel, gridConstraints); elapsedLabel.setText("Elapsed Time (sec)"); //label gridConstraints.gridx = 1; gridConstraints.gridy = 2; getContentPane().add(elapsedLabel, gridConstraints); startTextField.setText(""); startTextField.setColumns(15); //text field for Start time gridConstraints.gridx = 2; gridConstraints.gridy = 0; getContentPane().add(startTextField, new GridBagConstraints()); stopTextField.setText(""); //text field for Stop time stopTextField.setColumns(15); gridConstraints.gridx = 2; gridConstraints.gridy = 1;
  • 242. getContentPane().add(stopTextField, gridConstraints); elapsedTextField.setText(""); //text field for Elapsed time elapsedTextField.setColumns(15); gridConstraints.gridx = 2; gridConstraints.gridy = 2; getContentPane().add(elapsedTextField, gridConstraints); pack(); } //the following event method is performed with click of Start button private void startButtonActionPerformed(ActionEvent e) { // click of start timing button startTime = System.currentTimeMillis(); startTextField.setText(String.valueOf(startTime)); stopTextField.setText(""); elapsedTextField.setText(""); } //the following event method is performed with click of Stop button private void stopButtonActionPerformed(ActionEvent e) { // click of stop timing button stopTime = System.currentTimeMillis(); stopTextField.setText(String.valueOf(stopTime)); elapsedTime = (stopTime - startTime) / 1000.0; elapsedTextField.setText(String.valueOf(elapsedTime)); }
  • 243. //the method for closing and exiting the frame private void exitButtonActionPerformed(ActionEvent e) { System.exit(0); } private void exitForm(WindowEvent e) { System.exit(0); } } EX18. Savings Account This project determines how much you save by making monthly deposits into a savings account. The mathematical formula used is: F = D[(1 + I)M – 1)] / I where F - Final amount D - Monthly deposit amount I - Monthly interest rate M - Number of months Savings Account GUI class 1. For this class, first start with the basic GUI template package savings.account; import javax.swing.*; import java.awt.*; import java.awt.event.*; public class SavingsAccount extends JFrame { public static void main(String[] args) { //Construct the frame (by calling the SavingsAccount() constructor) new SavingsAccount().show(); } public SavingsAccount() //constructor { //code to build the form and add all its elements setTitle("Savings Account"); addWindowListener(new WindowAdapter() {
  • 244. public void windowClosing(WindowEvent e) { exitForm(e); } }); getContentPane().setLayout(new GridBagLayout()); } private void exitForm(WindowEvent e) { System.exit(0); } } ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~` 2. The layout used GridBagLayout form takes this shape X = 0 X = 1 Y= 0 deposit Label depositTextField Y= 1 yearly Interest Label interestTextField Y = 2 number OfMonths Label monthsTextField Y = 3 finalBalance Label finalTextField Y = 4 calculateButton Exit Button ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~` 3. And this is the final product ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~` NEXT YOU WRITE THE CODES AS FOLLOWS
  • 245. package savings.account; import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.text.*; public class SavingsAccount extends JFrame { //add the needed controls for the class JLabel depositLabel = new JLabel(); JLabel interestLabel = new JLabel(); JLabel monthsLabel = new JLabel(); JLabel finalLabel = new JLabel(); JTextField depositTextField = new JTextField(); JTextField interestTextField = new JTextField(); JTextField monthsTextField = new JTextField(); JTextField finalTextField = new JTextField(); JButton calculateButton = new JButton(); JButton exitButton = new JButton(); //next comes the main class that houses the constructor public static void main(String args[]) { //construct frame - the main calls the SavingsAccount() constructor below new SavingsAccount().show(); } public SavingsAccount() //this is the SavingsAccount() constructor { // code to build the form and add all its elements are placed here setTitle("Savings Account"); addWindowListener(new WindowAdapter() //this code for Exit of the { //form with click of X button public void windowClosing(WindowEvent e) { exitForm(e); } }); // position controls on the form (& establish event methods) getContentPane().setLayout(new GridBagLayout()); GridBagConstraints gridConstraints = new GridBagConstraints(); depositLabel.setText("Monthly Deposit");
  • 246. gridConstraints.gridx = 0; gridConstraints.gridy = 0; getContentPane().add(depositLabel, gridConstraints); interestLabel.setText("Yearly Interest"); gridConstraints.gridx = 0; gridConstraints.gridy = 1; getContentPane().add(interestLabel, gridConstraints); monthsLabel.setText("Number of Months"); gridConstraints.gridx = 0; gridConstraints.gridy = 2; getContentPane().add(monthsLabel, gridConstraints); finalLabel.setText("Final Balance"); gridConstraints.gridx = 0; gridConstraints.gridy = 3; getContentPane().add(finalLabel, gridConstraints); depositTextField.setText(""); depositTextField.setColumns(10); gridConstraints.gridx = 1; gridConstraints.gridy = 0; getContentPane().add(depositTextField, gridConstraints); interestTextField.setText(""); interestTextField.setColumns(10); gridConstraints.gridx = 1; gridConstraints.gridy = 1; getContentPane().add(interestTextField, gridConstraints); monthsTextField.setText(""); monthsTextField.setColumns(10); gridConstraints.gridx = 1; gridConstraints.gridy = 2; getContentPane().add(monthsTextField, gridConstraints); finalTextField.setText(""); finalTextField.setFocusable(false); finalTextField.setColumns(10); gridConstraints.gridx = 1; gridConstraints.gridy = 3; getContentPane().add(finalTextField, gridConstraints);
  • 247. calculateButton.setText("Calculate"); //this button has the gridConstraints.gridx = 0; //ActionListener placed after its placement gridConstraints.gridy = 5; getContentPane().add(calculateButton, gridConstraints); calculateButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) //actionPerformed with { //the click of Calculate button calculateButtonActionPerformed(e); } }); exitButton.setText("Exit"); //Closes the SavingsAccount form exitButton.setFocusable(false); gridConstraints.gridx = 1; gridConstraints.gridy = 5; getContentPane().add(exitButton, gridConstraints); exitButton.addActionListener(new ActionListener() //ActionListener for Exit button { public void actionPerformed(ActionEvent e) //actionPerformed on click of Exit button { exitButtonActionPerformed(e); } }); pack(); } //marking the end of the GridBagLout and its contents //ActionPerformed events along with the variables and the methods that run to do the calculations // go here. The codes for the two //events are placed immediately following the constructor private void calculateButtonActionPerformed(ActionEvent e) { double deposit; double interest; double months; double finalBalance; double monthlyInterest;
  • 248. // read values from text fields deposit = Double.valueOf(depositTextField.getText()).doubleValue(); interest = Double.valueOf(interestTextField.getText()).doubleValue(); monthlyInterest = interest / 1200; months = Double.valueOf(monthsTextField.getText()).doubleValue(); // compute final value and put the value in the text field; finalBalance = deposit * (Math.pow((1 + monthlyInterest), months) - 1) / monthlyInterest; finalTextField.setText(new DecimalFormat("0.00").format(finalBalance)); } //actionPerformed on click of Exit button private void exitButtonActionPerformed(ActionEvent e) { System.exit(0); } private void exitForm(WindowEvent e) //the Exit Window method { System.exit(0); } }
  • 249. EX19: Password Validation Example package password; import javax.swing.*; import java.awt.*; import java.awt.event.*; public class Password extends JFrame { JLabel passwordLabel = new JLabel(); JPasswordField inputPasswordField = new JPasswordField(); JButton validButton = new JButton(); JButton exitButton = new JButton(); public static void main(String args[]) { //construct frame new Password().show();
  • 250. } public Password() { // code to build the form setTitle("Password Validation"); setResizable(false); getContentPane().setBackground(Color.yellow); //this code is window closing ActionListener addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { exitForm(e); } }); // position controls getContentPane().setLayout(new GridBagLayout()); GridBagConstraints gridConstraints; passwordLabel.setText("Please Enter Your Password:"); passwordLabel.setOpaque(true); passwordLabel.setBackground(Color.white); passwordLabel.setFont(new Font("Arial", Font.BOLD, 14)); passwordLabel.setBorder(BorderFactory.createLoweredBevelBorder()); passwordLabel.setHorizontalAlignment(SwingConstants.CENTER); gridConstraints = new GridBagConstraints(); gridConstraints.ipadx = 30; gridConstraints.ipady = 20; gridConstraints.gridx = 0; gridConstraints.gridy = 0; gridConstraints.insets = new Insets(5, 20, 5, 20); getContentPane().add(passwordLabel, gridConstraints); inputPasswordField.setText(""); inputPasswordField.setFont(new Font("Arial", Font.PLAIN, 14)); inputPasswordField.setColumns(15); gridConstraints = new GridBagConstraints(); gridConstraints.gridx = 0; gridConstraints.gridy = 1; getContentPane().add(inputPasswordField, gridConstraints);
  • 251. inputPasswordField.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { inputPasswordFieldActionPerformed(e); } }); validButton.setText("Validate"); gridConstraints = new GridBagConstraints(); gridConstraints.gridx = 0; gridConstraints.gridy = 2; getContentPane().add(validButton, gridConstraints); validButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { validButtonActionPerformed(e); } }); exitButton.setText("Exit"); gridConstraints = new GridBagConstraints(); gridConstraints.gridx = 0; gridConstraints.gridy = 3; getContentPane().add(exitButton, gridConstraints); exitButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { exitButtonActionPerformed(e); } }); pack(); //This code set the password screen at the centre of the monitor Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); setBounds((int) (0.5 * (screenSize.width - getWidth())), (int) (0.5 * (screenSize.height - getHeight())), getWidth(), getHeight()); }
  • 252. private void inputPasswordFieldActionPerformed(ActionEvent e) { validButton.doClick(); } private void validButtonActionPerformed(ActionEvent e) { final String THEPASSWORD = "LetMeIn"; //This procedure checks the input password int response; if (inputPasswordField.getText().equals(THEPASSWORD)) { // If correct, display message box JOptionPane.showConfirmDialog(null, "You've passed security!", "Access Granted", JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE); } else { // If incorrect, give option to try again response = JOptionPane.showConfirmDialog(null, "Incorrect password - Try Again?", "AccessDenied", JOptionPane.YES_NO_OPTION, JOptionPane.ERROR_MESSAGE); if (response == JOptionPane.YES_OPTION) { inputPasswordField.setText(""); inputPasswordField.requestFocus(); } else { exitButton.doClick(); } } } private void exitButtonActionPerformed(ActionEvent e) { System.exit(0); } private void exitForm(WindowEvent e) { System.exit(0);
  • 253. } }
  • 254. EX 20. Pizza Order Form
  • 255. package pizza; import javax.swing.*; import java.awt.*; import java.awt.event.*; public class Pizza extends javax.swing.JFrame { JPanel sizePanel = new JPanel(); //these are class level declarations ButtonGroup sizeButtonGroup = new ButtonGroup(); JRadioButton smallRadioButton = new JRadioButton(); JRadioButton mediumRadioButton = new JRadioButton(); JRadioButton largeRadioButton = new JRadioButton(); JPanel crustPanel = new JPanel(); ButtonGroup crustButtonGroup = new ButtonGroup(); JRadioButton thinRadioButton = new JRadioButton(); JRadioButton thickRadioButton = new JRadioButton(); JPanel toppingsPanel = new JPanel(); JCheckBox cheeseCheckBox = new JCheckBox(); JCheckBox mushroomsCheckBox = new JCheckBox(); JCheckBox olivesCheckBox = new JCheckBox(); JCheckBox onionsCheckBox = new JCheckBox(); JCheckBox peppersCheckBox = new JCheckBox(); JCheckBox tomatoesCheckBox = new JCheckBox(); ButtonGroup whereButtonGroup = new ButtonGroup(); JRadioButton eatInRadioButton = new JRadioButton(); JRadioButton takeOutRadioButton = new JRadioButton(); JButton buildButton = new JButton(); JButton exitButton = new JButton(); String pizzaSize; String pizzaCrust; String pizzaWhere; JCheckBox[] topping = new JCheckBox[6]; public static void main(String args[]) { // construct frame new Pizza().show(); } public Pizza() { setTitle("Pizza Order"); setResizable(true); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) {
  • 256. exitForm(e); } }); getContentPane().setLayout(new GridBagLayout()); //ContentPane hold all the controls GridBagConstraints gridConstraints; //position controls sizePanel.setLayout(new GridBagLayout()); sizePanel.setBorder(BorderFactory.createTitledBorder("Size")) ; smallRadioButton.setText("Small"); smallRadioButton.setSelected(true); sizeButtonGroup.add(smallRadioButton); //you add smallRadioButton to sizeButtonGroup gridConstraints = new GridBagConstraints(); gridConstraints.gridx = 0; gridConstraints.gridy = 0; gridConstraints.anchor = GridBagConstraints.WEST; sizePanel.add(smallRadioButton, gridConstraints); //you also add button to panel smallRadioButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { sizeRadioButtonActionPerformed(e); } }); mediumRadioButton.setText("Medium"); sizeButtonGroup.add(mediumRadioButton); gridConstraints = new GridBagConstraints(); gridConstraints.gridx = 0; gridConstraints.gridy = 1; gridConstraints.anchor = GridBagConstraints.WEST; sizePanel.add(mediumRadioButton, gridConstraints); mediumRadioButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { sizeRadioButtonActionPerformed(e); } }); largeRadioButton.setText("Large"); largeRadioButton.setSelected(true); sizeButtonGroup.add(largeRadioButton); gridConstraints = new GridBagConstraints(); gridConstraints.gridx = 0;
  • 257. gridConstraints.gridy = 2; gridConstraints.anchor = GridBagConstraints.WEST; sizePanel.add(largeRadioButton, gridConstraints); largeRadioButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { sizeRadioButtonActionPerformed(e); } }); gridConstraints = new GridBagConstraints(); gridConstraints.gridx = 0; gridConstraints.gridy = 0; getContentPane().add(sizePanel, gridConstraints); crustPanel.setLayout(new GridBagLayout()); crustPanel.setBorder(BorderFactory.createTitledBorder("Crust")); thinRadioButton.setText("Thin Crust"); thinRadioButton.setSelected(true); crustButtonGroup.add(thinRadioButton); gridConstraints = new GridBagConstraints(); gridConstraints.gridx = 0; gridConstraints.gridy = 0; gridConstraints.anchor = GridBagConstraints.WEST; crustPanel.add(thinRadioButton, gridConstraints); thinRadioButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { crustRadioButtonActionPerformed(e); } }); thickRadioButton.setText("Thick Crust"); crustButtonGroup.add(thickRadioButton); gridConstraints = new GridBagConstraints(); gridConstraints.gridx = 0; gridConstraints.gridy = 1; gridConstraints.anchor = GridBagConstraints.WEST; crustPanel.add(thickRadioButton, gridConstraints); thickRadioButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { crustRadioButtonActionPerformed(e);
  • 258. } }); gridConstraints = new GridBagConstraints(); gridConstraints.gridx = 0; gridConstraints.gridy = 1; getContentPane().add(crustPanel, gridConstraints); //you add the crustPanel to ContentPane toppingsPanel.setLayout(new GridBagLayout()); toppingsPanel.setBorder(BorderFactory.createTitledBorder("Toppings")) ; cheeseCheckBox.setText("Extra Cheese"); gridConstraints = new GridBagConstraints(); gridConstraints.gridx = 0; gridConstraints.gridy = 0; gridConstraints.anchor = GridBagConstraints.WEST; toppingsPanel.add(cheeseCheckBox, gridConstraints); mushroomsCheckBox.setText("Mushrooms"); gridConstraints = new GridBagConstraints(); gridConstraints.gridx = 0; gridConstraints.gridy = 1; gridConstraints.anchor = GridBagConstraints.WEST; toppingsPanel.add(mushroomsCheckBox, gridConstraints); olivesCheckBox.setText("Olives"); gridConstraints = new GridBagConstraints(); gridConstraints.gridx = 0; gridConstraints.gridy = 2; gridConstraints.anchor = GridBagConstraints.WEST; toppingsPanel.add(olivesCheckBox, gridConstraints); onionsCheckBox.setText("Onions"); gridConstraints = new GridBagConstraints(); gridConstraints.gridx = 1; gridConstraints.gridy = 0; gridConstraints.anchor = GridBagConstraints.WEST; toppingsPanel.add(onionsCheckBox, gridConstraints); peppersCheckBox.setText("Green Peppers"); gridConstraints = new GridBagConstraints(); gridConstraints.gridx = 1; gridConstraints.gridy = 1; gridConstraints.anchor = GridBagConstraints.WEST; toppingsPanel.add(peppersCheckBox, gridConstraints); tomatoesCheckBox.setText("Tomatoes"); gridConstraints = new GridBagConstraints();
  • 259. gridConstraints.gridx = 1; gridConstraints.gridy = 2; gridConstraints.anchor = GridBagConstraints.WEST; toppingsPanel.add(tomatoesCheckBox, gridConstraints); gridConstraints = new GridBagConstraints(); gridConstraints.gridx = 1; gridConstraints.gridy = 0; gridConstraints.gridwidth = 2; getContentPane().add(toppingsPanel, gridConstraints); //adds the toppingsPanel //to the Content Pane eatInRadioButton.setText("Eat In"); eatInRadioButton.setSelected(true); whereButtonGroup.add(eatInRadioButton); gridConstraints = new GridBagConstraints(); gridConstraints.gridx = 1; gridConstraints.gridy = 1; gridConstraints.anchor = GridBagConstraints.WEST; getContentPane().add(eatInRadioButton, gridConstraints); eatInRadioButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { whereRadioButtonActionPerformed(e); } }); takeOutRadioButton.setText("Take Out"); whereButtonGroup.add(takeOutRadioButton); gridConstraints = new GridBagConstraints(); gridConstraints.gridx = 2; gridConstraints.gridy = 1; gridConstraints.anchor = GridBagConstraints.WEST; getContentPane().add(takeOutRadioButton, gridConstraints); takeOutRadioButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { whereRadioButtonActionPerformed(e); } }); buildButton.setText("Build Pizza"); gridConstraints = new GridBagConstraints(); gridConstraints.gridx = 1;
  • 260. gridConstraints.gridy = 2; getContentPane().add(buildButton, gridConstraints); buildButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { buildButtonActionPerformed(e); } }); exitButton.setText("Exit"); gridConstraints = new GridBagConstraints(); gridConstraints.gridx = 2; gridConstraints.gridy = 2; getContentPane().add(exitButton, gridConstraints); exitButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { exitButtonActionPerformed(e); } }); pack(); //the following lines of code centralize the Pizza order form Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); setBounds((int) (0.5 * (screenSize.width - getWidth())), (int) (0.5 * (screenSize.height - getHeight())), getWidth(), getHeight()); // Initialize parameters pizzaSize = smallRadioButton.getText(); pizzaCrust = thinRadioButton.getText(); pizzaWhere = eatInRadioButton.getText(); // Define an array of topping check boxes topping[0] = cheeseCheckBox; topping[1] = mushroomsCheckBox; topping[2] = olivesCheckBox; topping[3] = onionsCheckBox; topping[4] = peppersCheckBox; topping[5] = tomatoesCheckBox; } private void sizeRadioButtonActionPerformed(ActionEvent e) { pizzaSize = e.getActionCommand();
  • 261. } private void crustRadioButtonActionPerformed(ActionEvent e) { pizzaCrust = e.getActionCommand(); } private void whereRadioButtonActionPerformed(ActionEvent e) { pizzaWhere = e.getActionCommand(); } private void buildButtonActionPerformed(ActionEvent e) { // This procedure builds a confirm dialog box that displays your pizza type String message; message = pizzaWhere + "n"; message += pizzaSize + " Pizza" + "n"; message += pizzaCrust + "n"; // Check each topping using the array we set up for (int i = 0; i < 6; i++) { if (topping[i].isSelected()) { message += topping[i].getText() + "n"; } } JOptionPane.showConfirmDialog(null, message, "Your Pizza", JOptionPane.DEFAULT_OPTION, JOptionPane.INFORMATION_MESSAGE); } private void exitButtonActionPerformed(ActionEvent e) { System.exit(0); } private void exitForm(WindowEvent e) { System.exit(0); } }
  • 262. EX 21: Flight Planner On running the application and clicking assign, we have; package flight; import javax.swing.*; import java.awt.*; import java.awt.event.*; public class Flight extends JFrame { //class wide labels added below as needed JLabel citiesLabel = new JLabel(); JList citiesList = new JList(); JScrollPane citiesScrollPane = new JScrollPane(); JLabel seatLabel = new JLabel(); JComboBox seatComboBox = new JComboBox(); JLabel mealLabel = new JLabel();
  • 263. JComboBox mealComboBox = new JComboBox(); JButton assignButton = new JButton(); JButton exitButton = new JButton(); public static void main(String[] args) { // Construct frame new Flight().show(); } public Flight() { //Create frame setTitle("Flight Planner"); setResizable(false); addWindowListener(new WindowAdapter() //for exiting on clicking X on the form { public void windowClosing(WindowEvent e) { exitForm(e); } }); getContentPane().setLayout(new GridBagLayout()); //type of layout for the ContentPane GridBagConstraints gridConstraints; //creating layout type which is GridBag citiesLabel.setText("Destination City"); // add citiesLabel to GridBag gridConstraints = new GridBagConstraints(); gridConstraints.gridx = 0; gridConstraints.gridy = 0; gridConstraints.insets = new Insets(10, 0, 0, 0); getContentPane().add(citiesLabel, gridConstraints); //adds citiesLabel to ContentPane citiesScrollPane.setPreferredSize(new Dimension(150, 100)); //position ScrollPane in GridBag citiesScrollPane.setViewportView(citiesList); gridConstraints = new GridBagConstraints(); gridConstraints.gridx = 0; gridConstraints.gridy = 1;
  • 264. gridConstraints.insets = new Insets(10, 10, 10, 10); getContentPane().add(citiesScrollPane, gridConstraints); //adds ScrollPane to ContentPane DefaultListModel citiesListModel = new DefaultListModel(); // list of cities citiesListModel.addElement("San Diego"); citiesListModel.addElement("Los Angeles"); citiesListModel.addElement("Orange County"); citiesListModel.addElement("Ontario"); citiesListModel.addElement("Bakersfield"); citiesListModel.addElement("Oakland"); citiesListModel.addElement("Sacramento"); citiesListModel.addElement("San Jose"); citiesListModel.addElement("San Francisco"); citiesListModel.addElement("Eureka"); citiesListModel.addElement("Eugene"); citiesListModel.addElement("Portland"); citiesListModel.addElement("Spokane"); citiesListModel.addElement("Seattle"); citiesList.setModel(citiesListModel); citiesList.setSelectedIndex(0); seatLabel.setText("Seat Location"); // seatLabel positioned in GridBag gridConstraints = new GridBagConstraints(); gridConstraints.gridx = 1; gridConstraints.gridy = 0; gridConstraints.insets = new Insets(10, 0, 0, 0); getContentPane().add(seatLabel, gridConstraints); // seatLabel added to ContentPane seatComboBox.setBackground(Color.YELLOW); // position ComboBox in the GridBag seatComboBox.setPreferredSize(new Dimension(100, 25)); gridConstraints = new GridBagConstraints(); gridConstraints.gridx = 1; gridConstraints.gridy = 1; gridConstraints.insets = new Insets(10, 0, 0, 0); gridConstraints.anchor = GridBagConstraints.NORTH; getContentPane().add(seatComboBox, gridConstraints); // adding the seatComboBox to ContentPane seatComboBox.addItem("Aisle"); // seatComboBox items
  • 265. seatComboBox.addItem("Middle"); seatComboBox.addItem("Window"); seatComboBox.setSelectedIndex(0); mealLabel.setText("Meal Preference"); // mealLabel positioned in GridBag gridConstraints = new GridBagConstraints(); gridConstraints.gridx = 2; gridConstraints.gridy = 0; gridConstraints.insets = new Insets(10, 0, 0, 0); getContentPane().add(mealLabel, gridConstraints); // add mealLabel to ContentPane mealComboBox.setEditable(true); // mealComboBox added to the GridBag gridConstraints = new GridBagConstraints(); gridConstraints.gridx = 2; gridConstraints.gridy = 1; gridConstraints.insets = new Insets(10, 10, 0, 10); gridConstraints.anchor = GridBagConstraints.NORTH; getContentPane().add(mealComboBox, gridConstraints); // add mealBoxCombo to ContentPane mealComboBox.setSelectedItem("No Preference"); // mealComboBox items mealComboBox.addItem("Chicken"); mealComboBox.addItem("Mystery Meat"); mealComboBox.addItem("Kosher"); mealComboBox.addItem("Vegetarian"); mealComboBox.addItem("Fruit Plate"); assignButton.setText("Assign"); // add assignButton to the GridBag gridConstraints = new GridBagConstraints(); gridConstraints.gridx = 1; gridConstraints.gridy = 2; gridConstraints.insets = new Insets(0, 0, 10, 0); getContentPane().add(assignButton, gridConstraints); // add assignButton to ContentPane assignButton.addActionListener(new ActionListener() // assignButton ActionListener { public void actionPerformed(ActionEvent e)
  • 266. { assignButtonActionPerformed(e); } }); exitButton.setText("Exit"); // adds exitButton to the GridBag layout gridConstraints = new GridBagConstraints(); gridConstraints.gridx = 2; gridConstraints.gridy = 2; gridConstraints.insets = new Insets(0,0,10, 0); getContentPane().add(exitButton, gridConstraints); // adds exitButton to ContentPane exitButton.addActionListener(new ActionListener() // ActionListener for exitButton { public void actionPerformed(ActionEvent e) { exitButtonActionPerformed(e); } }); pack(); // this line ends the GridBagLayout setting // The next lines of code centers the form in the middle of the computer screen Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); setBounds((int) (0.5*(screenSize.width = getWidth())), (int) (0.5*(screenSize.height - getHeight())), getWidth(), getHeight()); } private void exitForm(WindowEvent e) // method for exitForm on click of exitButton { System.exit(0); } // the method below performs what happens on click of assignButton private void assignButtonActionPerformed(ActionEvent e) { // Build message box that gives your assignment String message; message = "Destination: " + citiesList.getSelectedValue() + "n"; message += "Seat Location: " + seatComboBox.getSelectedItem() + "n";
  • 267. message += "Meal: " + mealComboBox.getSelectedItem() + "n"; JOptionPane.showConfirmDialog(null, message, "Your Assignment", JOptionPane.DEFAULT_OPTION, JOptionPane.INFORMATION_MESSAGE); } //the method below exits the application on click of exitButton private void exitButtonActionPerformed(ActionEvent e) { System.exit(0); } }
  • 268. Next CHALLENGE Question 2 - Page 115 In the “Game Zone” section in Chapter 1, you learned how to obtain a random number. For example, the following statement generates a random number between the constants MIN and MAX inclusive and assigns it to a variable named random: random = 1 + (int)(Math.random() * MAX); Write a program that selects a random number between 1 and 5 and asks the user to guess the number. Display a message that indicates the difference between the random number and the user’s guess. Display another message that displays the random number and the Boolean value true or false depending on whether the user’s guess equals the random number. Save the file as RandomGuessMatch.java. Page 116 = Case Problems Case Problems 1. Carly’s Catering provides meals for parties and special events. Write a program that prompts the user for the number of guests attending an event and then computes the total price, which is $35 per person. Display the company motto with the border that you created in the CarlysMotto2 class in Chapter 1, and then display the number of guests, price per guest, and total price. Also display a message that indicates true or false epending on whether the job is classified as a large event—an event with 50 or more guests. Save the file as CarlysEventPrice.java. 2. Sammy’s Seashore Supplies rents beach equipment such as kayaks, canoes, beach chairs, and umbrellas to tourists. Write a program that prompts the user for the number of minutes he rented a piece of sports equipment. Compute the rental cost as $40 per hour plus $1 per additional minute. (You might have surmised
  • 269. already that this rate has a logical flaw, but for now, calculate rates as described here. You can fix the problem after you read the chapter on decision making.) Display Sammy’s motto with the border that you created in the SammysMotto2 class in Chapter 1. Then display the hours, minutes, and total price. Save the file as SammysRentalPrice.java. Page 237 – Gregorian Calendar 8. Write an application that uses methods in the GregorianCalendar class to calculate how many days are left until the first day of next month. Save the file as NextMonth.java. 9. Write an application that uses methods in the GregorianCalendar class to calculate the number of days from today until the end of the current year. Save the file as YearEnd.java.