You are on page 1of 89

Introduction to

Java
Programming

Workshop
Solutions
Introduction to Java Programing: Workshop Solutions Page i

Table of Contents

Chapter 1: HelloWorld Workshop ................................................................................................1


Chapter 2: Control Structures Workshop ...................................................................................2
Chapter 2: HelloWorld Arguments Workshop.............................................................................4
Chapter 4: Using Objects Workshop............................................................................................5
Chapter 4: More Objects Workshop .............................................................................................6
Chapter 5: Create Classes Workshop A ......................................................................................8
Chapter 5: Create Class Workshop B...........................................................................................9
Chapter 5: Create Class Workshop C.........................................................................................11
Chapter 6: Packages Workshop .................................................................................................14
Chapter 7: Inheritance Workshop A ...........................................................................................15
Chapter 7: Inheritance Workshop B ...........................................................................................18
Chapter 8: Polymorphism Workshop .........................................................................................23
Chapter 11: HelloWorld Applet Workshop.................................................................................28
Chapter 12: Components Workshop ..........................................................................................30
Chapter 13: Colors Workshop.....................................................................................................32
Chapter 14: Event Handling Workshop.....................................................................................34
Chapter 15: Collections Workshop............................................................................................38
Chapter 16: Inner Classes Workshop.........................................................................................39
Chapter 17: Throwing an Exception Workshop .......................................................................42
Chapter 17: Catching an Exception Workshop .........................................................................47
Chapter 18: Multi-Threading Workshop .....................................................................................52
Chapter 19: Swing Containers Workshop ................................................................................55
Chapter 20: Layout Manger Workshop .....................................................................................58
Chapter 21: Windowed Application Workshop ........................................................................61
Chapter 5 Advanced: Creating Classes .....................................................................................64
Chapter 7 Advanced: Inheritance ...............................................................................................68
Chapter 9 Advanced: Interfaces .................................................................................................71

© 2003 SkillBuilders Inc. V 5.4


Introduction to Java Programing: Workshop Solutions Page ii

Chapter 15 Advanced: Using Collections .................................................................................73


Chapter 17 Advanced: Exceptions .............................................................................................83
Chapter 18 Advanced: Multi-Threading ....................................................................................85

© 2003 SkillBuilders Inc. V 5.4


Introduction to Java Programing: Workshop Solutions Page 1

Chapter 1:
HelloWorld Workshop

HelloWorld.java

/*
* HelloWorld
*/
public class HelloWorld {
public static void main (String[] args) {
System.out.println("Hello World!!");
}
}

© 2003 SkillBuilders Inc. V 5.4


Introduction to Java Programing: Workshop Solutions Page 2

Chapter 2:
Control Structures Workshop

MultTable.java
/*
* MultTable class
*/

public class MultTable {


public static void main(String[] args) {
int iRows = 20, iCols = 10;

for(int r = 1; r <= iRows; ++r) { // Rows


for(int c = 1; c <= iCols; ++c) { // Columns
int iResult = r * c; // Calculate result

// Put in extra space to align number


if(iResult < 1000)
System.out.print(" "); // Extra space if 3 digits
if(iResult < 100)
System.out.print(" "); // Extra space if 2 digits
if(iResult < 10)
System.out.print(" "); // Extra space if 1 digit
System.out.print(iResult); // Print column value
}
System.out.println(); // End the row
}
} // end main()

} // end class

MultTableLabel.java
/*
* MultTableLabel
*
* Multiplication table program with row & column labels
* for "If Time" portion of lab.
*/

© 2003 SkillBuilders Inc. V 5.4


Introduction to Java Programing: Workshop Solutions Page 3

public class MultTableLabel {

public static void main(String[] args) {


int iRows = 20, iCols = 10;

System.out.print(" ");
for(int c = 1; c <= iCols; ++c) {
if(c < 10)
System.out.print(" ");
System.out.print(" " + c);
}
System.out.println();

System.out.print(" ");
for(int c = 1; c <= iCols; ++c)
System.out.print("====");
System.out.println();

for(int r = 1; r <= iRows; ++r) { // Rows


if(r < 10)
System.out.print(" ");
System.out.print(" " + r + "|");

for(int c = 1; c <= iCols; ++c) { // Columns


int iResult = r * c; // Calculate result

// Put in extra space to align number


if(iResult < 1000)
System.out.print(" "); // Extra space if 3 digits
if(iResult < 100)
System.out.print(" "); // Extra space if 2 digits
if(iResult < 10)
System.out.print(" "); // Extra space if 1 digit

System.out.print(iResult); // Print column value


}
System.out.println(); // End the row
}
} // end main()

} // end class MultTable

© 2003 SkillBuilders Inc. V 5.4


Introduction to Java Programing: Workshop Solutions Page 4

Chapter 2:
HelloWorld Arguments Workshop

HelloWorld.java
/*
* HelloWorld
*/
class HelloWorld {
public static void main (String[] args) {

// If no command line arguments, print Hello World


if (args.length == 0)
System.out.println("Hello World!!");
else {
System.out.println("You entered " + args.length +
" arguments:");
System.out.println();
int i;
for (i = 0; i < args.length; i++) {
System.out.println((i + 1) + ": " + args[i]);
}
}
}
}

© 2003 SkillBuilders Inc. V 5.4


Introduction to Java Programing: Workshop Solutions Page 5

Chapter 4:
Using Objects Workshop

DateDisplay.java
/*
* DateDisplay
*/

import java.util.*;
public class DateDisplay {
public static void main (String[] args) {
String[] month = {"January", "February", "March", "April", "May",
"June", "July", "August", "September", "October",
"November", "December" };
String [] dayOfWeek = {"Sunday", "Monday", "Tuesday", "Wednesday",
"Thursday", "Friday", "Saturday"};

GregorianCalendar myDate = new GregorianCalendar(2002, 2, 6);


System.out.print("The date I chose was ");
System.out.print(dayOfWeek[myDate.get(Calendar.DAY_OF_WEEK)-1]);
System.out.print(", ");

System.out.print(month[myDate.get(Calendar.MONTH) ]);
System.out.print(" ");
System.out.print(myDate.get(Calendar.DATE));
System.out.print(", ");
System.out.println(myDate.get(Calendar.YEAR));

GregorianCalendar todaysDate = new GregorianCalendar();


System.out.print("Today's date is ");
System.out.print
(dayOfWeek[todaysDate.get(Calendar.DAY_OF_WEEK)-1]);
System.out.print(", ");
System.out.print(month[todaysDate.get(Calendar.MONTH) ]);
System.out.print(" ");
System.out.print(todaysDate.get(Calendar.DATE));
System.out.print(", ");
System.out.println(todaysDate.get(Calendar.YEAR));
}
}

© 2003 SkillBuilders Inc. V 5.4


Introduction to Java Programing: Workshop Solutions Page 6

Chapter 4:
More Objects Workshop

DateDisplayXtra.java
/*
* Date DisplayXtra
*/
import java.util.*;
public class DateDisplayXtra {
public static void main (String[] args) {
String[] month = {"January", "February", "March", "April", "May",
"June", "July", "August", "September", "October",
"November", "December" };
String [] dayOfWeek = {"Sunday", "Monday", "Tuesday", "Wednesday",
"Thursday", "Friday", "Saturday"};

GregorianCalendar myDate;
String myString;

if (args.length == 3){
int userYear = Integer.parseInt(args[0]);
int userMonth = Integer.parseInt(args[1]);
int userDay = Integer.parseInt(args[2]);
myDate = new GregorianCalendar(userYear, userMonth , userDay);
myString = "The date you input was ";
}
else {
myString = "The date I chose was ";
myDate = new GregorianCalendar(2003, 2, 6);

}
System.out.println(myString
+ dayOfWeek[myDate.get(Calendar.DAY_OF_WEEK)-1]
+ ", "
+ month[myDate.get(Calendar.MONTH) ]

+ " "
+ myDate.get(Calendar.DATE)
+ ", "
+ myDate.get(Calendar.YEAR));

GregorianCalendar todaysDate = new GregorianCalendar();

© 2003 SkillBuilders Inc. V 5.4


Introduction to Java Programing: Workshop Solutions Page 7

System.out.println("Today's date is "


+ dayOfWeek[todaysDate.get(Calendar.DAY_OF_WEEK)-1]
+ ", "
+ month[todaysDate.get(Calendar.MONTH)]
+ " "
+ todaysDate.get(Calendar.DATE)
+ ", "
+ todaysDate.get(Calendar.YEAR));
}
}

© 2003 SkillBuilders Inc. V 5.4


Introduction to Java Programing: Workshop Solutions Page 8

Chapter 5:
Create Classes Workshop A

BigCorpCreateClassA.java
/*
* BigCorpCreateClassA - Create Class workshop A
*/
import java.util.*;
public class BigCorpCreateClassA {
public static void main (String[] args) {
Person myPerson1 = new Person();
myPerson1.setFName("Charlie");
myPerson1.setLName("Tuna");
System.out.println("My person is "
+ myPerson1.getFName()
+ " " + myPerson1.getLName());
myPerson1.walk();
myPerson1.talk();
}
}
class Person {
String lName;
String fName;
public void setLName(String inLName) {
lName = inLName;
}
public void setFName(String inFName) {
fName = inFName;
}
public String getLName() {
return lName;
}
public String getFName() {
return fName;
}
public void walk() {
System.out.println(getFName() + " " + getLName() + " is walking");
}
public void talk(){
System.out.println(getFName() + " " + getLName() + " is talking");
}
}

© 2003 SkillBuilders Inc. V 5.4


Introduction to Java Programing: Workshop Solutions Page 9

Chapter 5:
Create Class Workshop B

Using Static Variables

BigCorpCreateClassB.java
/*
* BigCorpCreateClassB - Using Static variables
*/
import java.util.*;

public class BigCorpCreateClassB {


public static void main (String[] args) {
Person myPerson1 = new Person();
myPerson1.setFName("Charlie");
myPerson1.setLName("Tuna");
System.out.println("My person is " + myPerson1.getFName()
+ " " + myPerson1.getLName());
myPerson1.walk();
myPerson1.talk();
System.out.println("the population is " + Person.getPopulation());

Person myPerson2 = new Person();


myPerson2.setFName("Harry");
myPerson2.setLName("Horse");
System.out.println("My person is " + myPerson2.getFName()
+ " " + myPerson2.getLName());
myPerson2.walk();
myPerson2.talk();
System.out.println("the population is " + Person.getPopulation());

myPerson1.finalize();
System.out.println("the population is " + Person.getPopulation());
}
}

class Person {
String lName;
String fName;
static long population;

public Person () {

© 2003 SkillBuilders Inc. V 5.4


Introduction to Java Programing: Workshop Solutions Page 10

population++;
}
public static long getPopulation () {
return population;
}

public void setLName(String inLName) {


lName = inLName;
}
public void setFName(String inFName) {
fName = inFName;
}

public String getLName() {


return lName;
}
public String getFName() {
return fName;
}
public void walk() {
System.out.println(getFName() + " " + getLName() + " is walking");
}
public void talk() {
System.out.println(getFName() + " " + getLName() + " is talking");
}

public void finalize() {


population --;
}
}

© 2003 SkillBuilders Inc. V 5.4


Introduction to Java Programing: Workshop Solutions Page 11

Chapter 5:
Create Class Workshop C

Constructors, this, Overloading

BigCorpCreateClassC.java
/*
* BigCorpCreateClassC - constructors, this & overloaded methods
*/

import java.util.*;

public class BigCorpCreateClassC {


public static void main (String[] args) {
Person myPerson1 = new Person();
myPerson1.setFName("Charlie");
myPerson1.setLName("Tuna");
System.out.println("My person is " + myPerson1.getFName()
+ " " + myPerson1.getLName());
myPerson1.walk();
myPerson1.talk();
myPerson1.setHeight(67);
System.out.println("the population is " + Person.getPopulation());
System.out.println("this person is height "
+ myPerson1.getHeight() );
System.out.println("the average height is "
+ Person.getAverageHeight());
System.out.println(" ");

// another person - use the simpler constructor...


Person myPerson2 = new Person("Robby", "Robot");
System.out.println("My person is " + myPerson2.getName());
myPerson2.talk("I am not a robot");
myPerson2.setHeight(73);
System.out.println("the population is " + Person.getPopulation());
System.out.println("this person is height "
+ myPerson2.getHeight() );
System.out.println("the average height is "
+ Person.getAverageHeight());
System.out.println(" ");

© 2003 SkillBuilders Inc. V 5.4


Introduction to Java Programing: Workshop Solutions Page 12

// get rid of one ...

myPerson1.finalize();
System.out.println("Remove " + myPerson1.getName()
+ " height was " + myPerson1.getHeight());
System.out.println("the population is " + Person.getPopulation());
System.out.println("the average height is "
+ Person.getAverageHeight());
System.out.println(" ");

// get rid of two ...


myPerson2.finalize();
System.out.println("Remove " + myPerson2.getName()
+ " height was "
+ myPerson2.getHeight());
System.out.println("this person is height "
+ myPerson2.getHeight() );
System.out.println("the average height is "
+ Person.getAverageHeight());
System.out.println("the population is " + Person.getPopulation());

}
}

class Person {

String lName;
String fName;
int height;

static long population;


static long totalHeight;
static float averageHeight;

public Person () {
population++;
}
public Person (String inFName, String inLName) {
this();
setLName(inLName);
setFName(inFName);
}

static long getPopulation () {


return population;
}

static float getAverageHeight() {


return averageHeight;
}
public void setLName(String inLName) {
lName = inLName;
}
public void setFName(String inFName) {
fName = inFName;
}
public String getLName() {

© 2003 SkillBuilders Inc. V 5.4


Introduction to Java Programing: Workshop Solutions Page 13

return lName;
}
public String getFName() {
return fName;
}
public String getName() {
return (fName + " " + lName);
}
public int getHeight() {
return height;
}
void setHeight(int inHeight) {
height = inHeight;
totalHeight += height;
setAverageHeight(height);
}

void setAverageHeight(int height) {


if (totalHeight != 0)
averageHeight = (float) totalHeight / population;
else
averageHeight = 0;
}
void walk() {
System.out.println(getFName() + " " + getLName() + " is walking");
}

public void talk() {


System.out.println(getFName() + " " + getLName() + " is talking");
}

public void talk(String speech) {


System.out.println(getFName() + " " + getLName()
+ " says: " + speech);
}

public void finalize() {


population --;
totalHeight -= this.height;
setAverageHeight(height);
}
}

© 2003 SkillBuilders Inc. V 5.4


Introduction to Java Programing: Workshop Solutions Page 14

Chapter 6:
Packages Workshop

Setenvpack.bat
Changes only applied to this statement:

set
CLASSPATH=.;c:\JavaIntro\workshops;c:\JavaIntro\lib\introcourse.jar;c:\J
avaIntro\lib\sbcourse.jar

BigCorpPack.java
/*
* BigCorpPack - Building Packages
*/

package com.skillbuilders;

Below this all is the same as BigVOrpCreateClassC

© 2003 SkillBuilders Inc. V 5.4


Introduction to Java Programing: Workshop Solutions Page 15

Chapter 7:
Inheritance Workshop A

BigCorpInheritA.java
/*
* BigCorpInheritA - Inheritance workshop A
*/

import java.util.*;

public class BigCorpInheritA {


public static void main (String[] args) {

Employee myEmpl1 = new Employee();


myEmpl1.setFName("John");
myEmpl1.setLName("Employee");
myEmpl1.setID("A1111");
System.out.println("My employee is " + myEmpl1.getName());
myEmpl1.pay();
myEmpl1.talk("I work harder");
myEmpl1.talk();
myEmpl1.personalOpinion();
System.out.println(" ");

Employee myEmpl2 = new Employee();


myEmpl2.setFName("Harry");
myEmpl2.setLName("Worker");
myEmpl2.setID("A2222");
System.out.println("My employee is " + myEmpl2.getName());
myEmpl2.pay();
myEmpl2.talk("I am the Boss");
myEmpl2.setHeight(76);
System.out.println("this employee is " + myEmpl2.getHeight()
+ " inches tall");
System.out.println(" ");

Employee myEmpl3 = new Employee("Mary", "Constructor", "A3333");


System.out.println("My employee is " + myEmpl3.getName()
+ " ID: " + myEmpl3.getID());
myEmpl3.pay();
myEmpl3.talk();
myEmpl3.walk();

© 2003 SkillBuilders Inc. V 5.4


Introduction to Java Programing: Workshop Solutions Page 16

}
}

class Person {
private String lName;
private String fName;
private int height;

private static long population;


private static long totalHeight;
private static float averageHeight;

public Person () {
population++;
}
public Person (String inFName, String inLName) {
this();
setLName(inLName);
setFName(inFName);
}

static long getPopulation () {


return population;
}

static float getAverageHeight() {


return averageHeight;
}

public void setLName(String inLName) {


lName = inLName;
}
public void setFName(String inFName) {
fName = inFName;
}
public String getLName() {
return lName;
}
public String getFName() {
return fName;
}
public String getName() {
return (fName + " " + lName);
}
public int getHeight() {
return height;
}
public void setHeight(int inHeight) {
height = inHeight;
totalHeight += height;
setAverageHeight(height);
}

void setAverageHeight(int height) {


if (totalHeight != 0)
averageHeight = (float) totalHeight / population;

© 2003 SkillBuilders Inc. V 5.4


Introduction to Java Programing: Workshop Solutions Page 17

else
averageHeight = 0;
}

void walk() {
System.out.println(getFName() + " " + getLName() + " is walking");
}

void talk() {
System.out.println(getFName() + " " + getLName() + " is talking");
}

void talk(String speech) {


System.out.println(getFName() + " " + getLName() + " says: "
+ speech);
}

public void finalize() {


population --;
totalHeight -= this.height;
setAverageHeight(height);
}
}
class Employee extends Person {
private String ID;
protected double wallet;

public Employee () {
}

public Employee (String inFName, String inLName, String ID) {


super(inFName, inLName);
setID(ID);
}

public String getID() {


return ID;
}
void setID(String ID) {
this.ID = ID;
}
public double getWallet() {
return wallet;
}

void pay() {
System.out.println(getFName() + " " + getLName() + " was paid");
}
public void talk() {
System.out.println("Speaking as an employee");
}
void personalOpinion() {
super.talk();
System.out.println("That is my personal opinion");
}
}

© 2003 SkillBuilders Inc. V 5.4


Introduction to Java Programing: Workshop Solutions Page 18

Chapter 7:
Inheritance Workshop B

BigCorpInheritB.java

/*
* BigCorpInheritB - Inheritance - abstract - final
*/

import java.util.*;

public class BigCorpInheritB {


public static void main (String[] args) {

// here's a wage employee


WageEmployee myEmpl1 =
new WageEmployee("john", "Wemployee", "Wage11", 40, 10);
System.out.println("My wage employee is " + myEmpl1.getName()
+ ", id number "
+ myEmpl1.getID());
myEmpl1.talk("I work harder");
myEmpl1.talk();
myEmpl1.personalOpinion();
System.out.println(" ");

// here's a salaried employee


SalariedEmployee myEmpl2 =
new SalariedEmployee("Harry", "Salworker", "Sal22", 400 );
System.out.println("My salaried employee is "
+ myEmpl2.getName()
+ ", id number "
+ myEmpl2.getID());
myEmpl2.talk("I am the Boss");
myEmpl2.setHeight(76);
System.out.println("this employee is " + myEmpl2.getHeight()
+ " inches tall");
System.out.println(" ");

// here's a Temp employee


TempEmployee myEmpl3 =
new TempEmployee("Robby", "Constructor", "Tmp33", 300, 55);
System.out.println("My Temp employee is " + myEmpl3.getName()

© 2003 SkillBuilders Inc. V 5.4


Introduction to Java Programing: Workshop Solutions Page 19

+ ", id number "


+ myEmpl3.getID());
myEmpl3.talk();
myEmpl3.walk();
System.out.println(" ");

// here's a Client
Client myClient1 = new Client("john", "Constructor", true);
System.out.println("My client is " + myClient1.getName()
+ ", their status is "
+ myClient1.isActive());
myClient1.setActive(false);
System.out.println("Now my client, " + myClient1.getName()
+ ", has status "
+ myClient1.isActive());
// Can't pay them - they're not an EMPLOYEE!
myClient1.talk();
myClient1.walk();
System.out.println(" ");

// pay my employees
myEmpl1.pay();
System.out.println(myEmpl1.getName() + "will be paid "
+ myEmpl1.getWallet());
myEmpl2.pay();
System.out.println(myEmpl2.getName() + " will be paid "
+ myEmpl2.getWallet());
myEmpl3.pay();
System.out.println(myEmpl3.getName() + " will be paid "
+ myEmpl3.getWallet());
}
}

abstract class Person {

private String lName;


private String fName;
private int height;

private static long population;


private static long totalHeight;
private static float averageHeight;

public Person () {
population++;
}
public Person (String inFName, String inLName) {
this();
setLName(inLName);
setFName(inFName);
}

static long getPopulation () {


return population;
}

static float getAverageHeight() {


return averageHeight;

© 2003 SkillBuilders Inc. V 5.4


Introduction to Java Programing: Workshop Solutions Page 20

public void setLName(String inLName) {


lName = inLName;
}
public void setFName(String inFName) {
fName = inFName;
}
public String getLName() {
return lName;
}
public String getFName() {
return fName;
}
public String getName() {
return (fName + " " + lName);
}
public int getHeight() {
return height;
}
public void setHeight(int inHeight) {
height = inHeight;
totalHeight += height;
setAverageHeight(height);
}

void setAverageHeight(int height) {


if (totalHeight != 0)
averageHeight = (float) totalHeight / population;
else
averageHeight = 0;
}

void walk() {
System.out.println(getFName() + " " + getLName()
+ " is walking");
}

void talk() {
System.out.println(getFName() + " " + getLName()
+ " is talking");
}

void talk(String speech) {


System.out.println(getFName() + " " + getLName()
+ " says: " + speech);
}

public void finalize(){


population --;
totalHeight -= this.height;
setAverageHeight(height);
}
}

abstract class Employee extends Person {


private String ID;
protected double wallet;

© 2003 SkillBuilders Inc. V 5.4


Introduction to Java Programing: Workshop Solutions Page 21

public Employee () {
}

public Employee (String inFName, String inLName, String ID) {


super(inFName, inLName);
this.ID = ID;
}

public String getID() {


return ID;
}
void setID(String ID) {
this.ID = ID;
}
public double getWallet() {
return wallet;
}

abstract void pay(); //abstract method has no body...

public void talk() {


System.out.println("Speaking as an employee");
}
void personalOpinion() {
super.talk();
System.out.println("That is my personal opinion");
}
}

final class Client extends Person {


private boolean active;

public boolean isActive() {


return active;
}
void setActive(boolean active){
this.active = active;
}

public Client (){


}

public Client (String inFName, String inLName, boolean active) {


super(inFName, inLName);
this.active = active;
}
}

final class WageEmployee extends Employee {


private double wage;
private double hours;

public WageEmployee () {
}

public WageEmployee (String inFName, String inLName,


String ID, double wage, double hours) {

© 2003 SkillBuilders Inc. V 5.4


Introduction to Java Programing: Workshop Solutions Page 22

super(inFName, inLName, ID);


this.wage = wage;
this.hours = hours;
}

void pay() {
wallet += (wage * hours);
}
}

final class SalariedEmployee extends Employee {


private double salary;

public SalariedEmployee () {
}

public SalariedEmployee (String inFName, String inLName,


String ID, double salary){
super(inFName, inLName, ID);
this.salary = salary;
}

void pay() {
wallet = salary;
}
}

final class TempEmployee extends Employee {


private double pay;
private double overtime;

public TempEmployee () {
}

public TempEmployee (String inFName, String inLName,


String ID, double pay, double overtime) {
super(inFName, inLName, ID);
this.pay= pay;
this.overtime = overtime;

void pay() {
wallet = pay + overtime;
}
}

© 2003 SkillBuilders Inc. V 5.4


Introduction to Java Programing: Workshop Solutions Page 23

Chapter 8:
Polymorphism Workshop

BigCorpPoly.java
/*
* BigCorpPoly - Polymorphism workshop
*/

package com.skillbuilders;
import java.util.*;

public class BigCorpPoly {


public static void main (String[] args) {
Employee [] staff = new Employee[3];

// here's a wage employee


WageEmployee myEmpl1 =
new WageEmployee("john", "Wemployee", "Wage11", 40, 10);
System.out.println("My wage employee is " + myEmpl1.getName()
+ ", id number "
+ myEmpl1.getID());
myEmpl1.talk("I work harder");
myEmpl1.talk();
myEmpl1.personalOpinion();
System.out.println(" ");

// here's a salaried employee


SalariedEmployee myEmpl2 =
new SalariedEmployee("Harry", "Salworker", "Sal22", 400 );
System.out.println("My salaried employee is " + myEmpl2.getName()
+ ", id number " + myEmpl2.getID());
System.out.println(myEmpl2.getName() + " will be paid "
+ myEmpl2.getWallet());
myEmpl2.talk("I am the Boss");
myEmpl2.setHeight(76);
System.out.println("this employee is " + myEmpl2.getHeight()
+ " inches tall");
System.out.println(" ");

// here's a Temp employee


TempEmployee myEmpl3 =
new TempEmployee("Robby", "Constructor", "Tmp33", 300, 55);

© 2003 SkillBuilders Inc. V 5.4


Introduction to Java Programing: Workshop Solutions Page 24

System.out.println("My Temp employee is " + myEmpl3.getName()


+ ", id number "
+ myEmpl3.getID());
myEmpl3.talk();
myEmpl3.walk();
System.out.println(" ");

// here's a Client
Client myClient1 = new Client("john", "Constructor", true);
System.out.println("My client is " + myClient1.getName()
+ ", their status is "
+ myClient1.isActive());
myClient1.setActive(false);
System.out.println("Now my client, " + myClient1.getName()
+ ", has status "
+ myClient1.isActive());
// Can't pay them - they're not an EMPLOYEE! ==> myClient1.pay();
myClient1.talk();
myClient1.walk();
System.out.println(" ");

// let's pay the employees


staff[0] = myEmpl1;
staff[1] = myEmpl2;
staff[2] = myEmpl3;

int i;
for (i = 0; i < staff.length; i++) {
staff[i].pay();
System.out.println(staff[i].getName() + " will be paid "
+ staff[i].getWallet());
}
}
}

abstract class Person {

private String lName;


private String fName;
private int height;

private static long population;


private static long totalHeight;
private static float averageHeight;

public Person () {
population++;
}
public Person (String inFName, String inLName) {
this();
setLName(inLName);
setFName(inFName);
}

static long getPopulation () {


return population;
}

© 2003 SkillBuilders Inc. V 5.4


Introduction to Java Programing: Workshop Solutions Page 25

static float getAverageHeight() {


return averageHeight;
}

public void setLName(String inLName) {


lName = inLName;
}
public void setFName(String inFName) {
fName = inFName;
}
public String getLName() {
return lName;
}
public String getFName() {
return fName;
}
public String getName() {
return (fName + " " + lName);
}
public int getHeight() {
return height;
}
public void setHeight(int inHeight) {
height = inHeight;
totalHeight += height;
setAverageHeight(height);
}

void setAverageHeight(int height) {


if (totalHeight != 0)
averageHeight = (float) totalHeight / population;
else
averageHeight = 0;
}

void walk() {
System.out.println(getFName() + " " + getLName()
+ " is walking");
}

void talk() {
System.out.println(getFName() + " " + getLName()
+ " is talking");
}

void talk(String speech) {


System.out.println(getFName() + " " + getLName()
+ " says: " + speech);
}

public void finalize(){


population --;
totalHeight -= this.height;
setAverageHeight(height);
}
}

abstract class Employee extends Person {

© 2003 SkillBuilders Inc. V 5.4


Introduction to Java Programing: Workshop Solutions Page 26

private String ID;


protected double wallet;

public Employee () {
}

public Employee (String inFName, String inLName, String ID) {


this.ID = ID;
}

public String getID() {


return ID;
}
void setID(String ID) {
this.ID = ID;
}
public double getWallet() {
return wallet;
}

abstract void pay(); //abstract method has no body...

public void talk() {


System.out.println("Speaking as an employee");
}
void personalOpinion() {
super.talk();
System.out.println("That is my personal opinion");
}
}

final class Client extends Person {


private boolean active;

public boolean isActive() {


return active;
}
void setActive(boolean active){
this.active = active;
}

public Client (){


}

public Client (String inFName, String inLName, boolean active) {


super(inFName, inLName);
this.active = active;
}
}

final class WageEmployee extends Employee {


private double wage;
private double hours;

public WageEmployee () {
}

public WageEmployee (String inFName, String inLName,

© 2003 SkillBuilders Inc. V 5.4


Introduction to Java Programing: Workshop Solutions Page 27

String ID, double wage, double hours) {


super(inFName, inLName, ID);
this.wage = wage;
this.hours = hours;
}

void pay() {
wallet += (wage * hours);
}
}

final class SalariedEmployee extends Employee {


private double salary;

public SalariedEmployee () {
}

public SalariedEmployee (String inFName, String inLName,


String ID, double salary){
super(inFName, inLName, ID);
this.salary = salary;
}

void pay() {
wallet = salary;
}
}

final class TempEmployee extends Employee {


private double pay;
private double overtime;

public TempEmployee () {
}

public TempEmployee (String inFName, String inLName,


String ID, double pay, double overtime) {
super(inFName, inLName, ID);
this.pay= pay;
this.overtime = overtime;

void pay() {
wallet = pay + overtime;
}
}

© 2003 SkillBuilders Inc. V 5.4


Introduction to Java Programing: Workshop Solutions Page 28

Chapter 11:
HelloWorld Applet Workshop

HelloWorld.java (starter)

/*
HelloWorld.java

Basic Hello World applet


*/

import java.applet.Applet;
import javax.swing.*;

public class HelloWorld extends Applet {


public void init() {
JLabel label = new JLabel("Hello\n\rWorld!");
add( label );
}
}

HelloWorld.html

<HTML>
<APPLET CODE="HelloWorld.class"
WIDTH=300
HEIGHT=200>
</APPLET>
</HTML>

HelloWorld.java (testing applet


methods workshop)

/*
HelloWorld.java

© 2003 SkillBuilders Inc. V 5.4


Introduction to Java Programing: Workshop Solutions Page 29

Enhanced Hello World applet exercise


(showing standard methods)
*/

import java.applet.Applet;
import javax.swing.*;

public class HelloWorld extends Applet {


private static int _iStaticCounter;
private int _iCounter;

public void init() {


JLabel label = new JLabel("Hello World!");
add( label );
_iCounter ++;
_iStaticCounter ++;
System.out.println("init invoked " + _iCounter + " times");
System.out.println("Static counter = " + _iStaticCounter);
}

public void start() {


System.out.println("start invoked");
}

public void stop() {


System.out.println("stop invoked");
}

public void destroy() {


System.out.println("destroy invoked");
}
}

© 2003 SkillBuilders Inc. V 5.4


Introduction to Java Programing: Workshop Solutions Page 30

Chapter 12:
Components Workshop

Sampler.java
/*
* Sampler - JButton, JTextField, JLabel
*/

package mylabs;

import javax.swing.*;

public class Sampler extends course.gui.BasicFrame {


private JTextField tfName ;
private JTextField tfPass ;
private JTextArea taAddress ;
private JButton btnOK ;
private JButton btnCancel ;

public void init() {


tfName = new JTextField(15);
tfPass = new JTextField(15);
taAddress = new JTextArea("", 10, 20);
btnOK = new JButton("OK");
btnCancel = new JButton("Cancel");

// Give buttons mnemonics


btnOK.setMnemonic('O');
btnCancel.setMnemonic('C');

// Put border around JTextArea


taAddress.setBorder( BorderFactory.createEtchedBorder() );

// Add components to applet


add(new JLabel("Name:"));
add(tfName);
add(new JLabel("Password:"));
add(tfPass);
add(new JLabel("Address:"));
add(taAddress);
add(btnOK);

© 2003 SkillBuilders Inc. V 5.4


Introduction to Java Programing: Workshop Solutions Page 31

add(btnCancel);

public static void main(String[] args) {


Sampler samp = new Sampler();
samp.setTitle("GUI Sampler");
}
}

© 2003 SkillBuilders Inc. V 5.4


Introduction to Java Programing: Workshop Solutions Page 32

Chapter 13:
Colors Workshop

Using Colors, Fonts and Borders

Sampler.java
// Sampler.java
// Exercise after lesson on Colors, Fonts & Borders

package mylabs;

import java.awt.*;
import javax.swing.*;

public class Sampler extends course.gui.BasicFrame {


private JTextField _tfName ;
private JTextField _tfPass ;
private JTextArea _taAddress ;
private JButton _btnOK ;
private JButton _btnCancel ;

public void init() {


_tfName = new JTextField(15);
_tfPass = new JTextField(15);
_taAddress = new JTextArea("", 10, 20);
_btnOK = new JButton("OK");
_btnCancel = new JButton("Cancel");

// Give buttons mnemonics


_btnOK.setMnemonic('O');
_btnCancel.setMnemonic('C');

// Set colors
setBackground( Color.lightGray ); // Window background
setForeground( Color.black ); // and foreground
_tfName.setBackground( Color.white );
_tfName.setForeground( Color.red );
_tfPass.setBackground( _tfName.getBackground() );
_tfPass.setForeground( _tfName.getForeground() );
_taAddress.setBackground( Color.white );

// Set fonts
_tfName.setFont( new Font( "Serif", Font.ITALIC, 20 ));
_tfPass.setFont( _tfName.getFont() );
_taAddress.setFont( new Font( "SansSerif", Font.BOLD, 16 ));

// Put titled border around JTextArea

© 2003 SkillBuilders Inc. V 5.4


Introduction to Java Programing: Workshop Solutions Page 33

_taAddress.setBorder( BorderFactory.createTitledBorder("Address") );

// Add components to applet


add(new JLabel("Name:"));
add(_tfName);
add(new JLabel("Password:"));
add(_tfPass);
// add(new JLabel("Address:"));
add(_taAddress);
add(_btnOK);
add(_btnCancel);
}

public static void main(String[] args) {


Sampler samp = new Sampler();
samp.setTitle("GUI Sampler");
}
}

© 2003 SkillBuilders Inc. V 5.4


Introduction to Java Programing: Workshop Solutions Page 34

Chapter 14:
Event Handling Workshop

Basic Event Handling

Sampler.java
/*
* Sampler.java - Event handling: Main part
*/
package mylabs;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class Sampler extends course.gui.BasicFrame


implements ActionListener {

private JTextField tfName ;


private JTextField tfPass ;
private JTextArea taAddress ;
private JButton btnOK ;
private JButton btnCancel ;

public void init() {


tfName = new JTextField(15);
tfPass = new JTextField(15);
taAddress = new JTextArea("", 10, 20);
btnOK = new JButton("OK");
btnCancel = new JButton("Cancel");

// Give buttons mnemonics


btnOK.setMnemonic('O');
btnCancel.setMnemonic('C');

// Set colors
setBackground( Color.lightGray ); // Applet background
setForeground( Color.black ); // and foreground
tfName.setBackground( Color.white );
tfName.setForeground( Color.red );
tfPass.setBackground( tfName.getBackground() );
tfPass.setForeground( tfName.getForeground() );
taAddress.setBackground( Color.white );

© 2003 SkillBuilders Inc. V 5.4


Introduction to Java Programing: Workshop Solutions Page 35

// Set fonts
tfName.setFont( new Font( "Serif", Font.ITALIC, 20 ));
tfPass.setFont( tfName.getFont() );
taAddress.setFont( new Font( "SansSerif", Font.BOLD, 16 ));

// Put titled border around JTextArea


taAddress.setBorder( BorderFactory.createTitledBorder("Address") );

// Add components to applet


add(new JLabel("Name:"));
add(tfName);
add(new JLabel("Password:"));
add(tfPass);
// add(new JLabel("Address:"));
add(taAddress);
add(btnCancel);

tfName.requestFocus(); // Start cursor in name field.

// Register listeners
btnOK.addActionListener( this );
btnCancel.addActionListener( this );

tfName.addActionListener( this );
tfPass.addActionListener( this );
}

public void actionPerformed( ActionEvent ae ) {


if( ae.getSource() == btnOK ) {
if(tfName.getText().equals("")) {
showStatus("You must enter a name.");
tfName.requestFocus();
}
else
showStatus("Greetings, " + tfName.getText());
}
else if( ae.getSource() == btnCancel ) {
tfName.setText("");
tfPass.setText("");
taAddress.setText("");
showStatus("");
tfName.requestFocus();
}
else if(ae.getSource() == tfName)
tfPass.requestFocus();
else if(ae.getSource() == tfPass)
taAddress.requestFocus();
}

public static void main(String[] args) {


Sampler samp = new Sampler();
samp.setTitle("GUI Sampler");
}
}

© 2003 SkillBuilders Inc. V 5.4


Introduction to Java Programing: Workshop Solutions Page 36

If you have time…


// Sampler.java
// Exercise after lesson on basic event handling: Optional part

package mylabs;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class Sampler extends course.gui.BasicFrame


implements ActionListener, KeyListener {

private JTextField tfName ;


private JTextField tfPass ;
private JTextArea taAddress ;
private JButton btnOK ;
private JButton btnCancel ;

public void init() {


tfName = new JTextField(15);
tfPass = new JTextField(15);
taAddress = new JTextArea("", 10, 20);
btnOK = new JButton("OK");
btnCancel = new JButton("Cancel");

// Give buttons mnemonics


btnOK.setMnemonic('O');
btnCancel.setMnemonic('C');

// Set colors
setBackground( Color.lightGray ); // Applet background
setForeground( Color.black ); // and foreground
tfName.setBackground( Color.white );
tfName.setForeground( Color.red );
tfPass.setBackground( tfName.getBackground() );
tfPass.setForeground( tfName.getForeground() );
taAddress.setBackground( Color.white );

// Set fonts
tfName.setFont( new Font( "Serif", Font.ITALIC, 20 ));
tfPass.setFont( tfName.getFont() );
taAddress.setFont( new Font( "SansSerif", Font.BOLD, 16 ));

// Put titled border around JTextArea


taAddress.setBorder( BorderFactory.createTitledBorder("Address") );

// Add components to applet


add(new JLabel("Name:"));
add(tfName);
add(new JLabel("Password:"));
add(tfPass);
// add(new JLabel("Address:"));
add(taAddress);
add(btnOK);
add(btnCancel);

© 2003 SkillBuilders Inc. V 5.4


Introduction to Java Programing: Workshop Solutions Page 37

btnOK.setEnabled(false); // OK button starts out disabled.


tfName.requestFocus(); // Start cursor in name field.

// Register listeners
btnOK.addActionListener( this );
btnCancel.addActionListener( this );

tfName.addActionListener( this );
tfPass.addActionListener( this );

tfName.addKeyListener( this );
tfPass.addKeyListener( this );
}

public void actionPerformed( ActionEvent ae ) {


if( ae.getSource() == btnOK ) {
if(tfName.getText().equals("")) {
showStatus("You must enter a name.");
tfName.requestFocus();
}
else
showStatus("Greetings, " + tfName.getText());
}
else if( ae.getSource() == btnCancel ) {
tfPass.setText("");
taAddress.setText("");
showStatus("");
tfName.requestFocus();
btnOK.setEnabled( false );
}
else if(ae.getSource() == tfName)
tfPass.requestFocus();
else if(ae.getSource() == tfPass)
taAddress.requestFocus();
}

public void keyReleased( KeyEvent ke ) {


if(tfName.getText().trim().equals("") ||
tfPass.getText().trim().equals(""))

btnOK.setEnabled( false );
else
btnOK.setEnabled( true );
}

public void keyPressed( KeyEvent ke ) {}


public void keyTyped( KeyEvent ke ) {}

public static void main(String[] args) {


Sampler samp = new Sampler();
samp.setTitle("GUI Sampler");
}
}

© 2003 SkillBuilders Inc. V 5.4


Introduction to Java Programing: Workshop Solutions Page 38

Chapter 15:
Collections Workshop

Using Collections

ListSystemProperties.java
import java.util.*;

public class ListSystemProperties {


public static void main( String[] args ) {
System.out.println( "System properties:" );
System.out.println( "Name = Value\n" );

Properties p = System.getProperties();
Enumeration e = p.propertyNames();
while( e.hasMoreElements() ) {
String strKey = (String) e.nextElement();
String strValue = p.getProperty( strKey, "Not found" );
System.out.println( strKey + " = " + strValue );
}
} // end of main()
} // end of class
of class

© 2003 SkillBuilders Inc. V 5.4


Introduction to Java Programing: Workshop Solutions Page 39

Chapter 16:
Inner Classes Workshop

Using Inner Classes

LinkedList.java
/*
LinkedList.java

Inner classes exercise


*/

package mylabs;

import java.io.*;
import java.util.Enumeration;

public class LinkedList {

// Private fields in LinkedList


private ListItem _liHead, _liTail;

// Methods
public void add( Object objData ) {
ListItem liNewItem = new ListItem( objData, null );

if( _liTail != null ) // Tack item on to old tail.


_liTail.setNext( liNewItem );
_liTail = liNewItem; // Added item is new tail.

// If no head, new item is new head.


if( _liHead == null )
_liHead = liNewItem;
}

public Enumeration elements() {


return new ListEnumeration();
}

public void loadFromFile( String strFileName )


throws IOException {

© 2003 SkillBuilders Inc. V 5.4


Introduction to Java Programing: Workshop Solutions Page 40

// BufferedReader adds line-reading capability.


FileReader fr = new FileReader( strFileName );
BufferedReader br = new BufferedReader( fr );

String line = br.readLine();


while( line != null ) {
add( line );
line = br.readLine();
}
fr.close();
}

public void printData( PrintStream dest ) {


dest.println( "Contents of list:\n" );
Enumeration e = elements();
while( e.hasMoreElements() )
dest.println( e.nextElement() );
}

// Inner classes
private class ListItem {
private Object _objData;
private ListItem _liNext;

// Constructor
public ListItem( Object objData, ListItem liNext ) {
_objData = objData; // Assign data.
setNext( liNext ); // Assign links.
}

// Methods
public Object getData( ) {
return _objData;
}
public ListItem getNext( ) {
return _liNext;
}
public void setNext( ListItem liNext ) {
_liNext = liNext;
}
} // End of ListItem class

private class ListEnumeration implements Enumeration {


private ListItem _liCurrItem = _liHead;

public boolean hasMoreElements() {


// As long as current item is not null,
// there are more elements.
return _liCurrItem != null;
}

public Object nextElement() {


// Return current data object after moving to
// next element.
Object retVal = _liCurrItem.getData();
_liCurrItem = _liCurrItem.getNext();
return retVal ;
}

© 2003 SkillBuilders Inc. V 5.4


Introduction to Java Programing: Workshop Solutions Page 41

} // End of ListEnumeration class


} // End of LinkedList class

Presidents.txt
Herbert Hoover
Franklin Roosevelt
Harry Truman
Dwight Eisenhower
John Kennedy
Richard Nixon
Gerald Ford
Jimmy Carter
Ronald Reagan
George Bush
Bill Clinton
George W. Bush

ListApp.java
// ListApp.java
package mylabs;

public class ListApp {


public static void main (String[] args) {
// Read list from file
if( args.length < 1 ) {
System.out.println(
"You must supply file name as 1st command line argument." );
System.exit(-1);
}

// Create empty linked list


LinkedList linkedlist = new LinkedList();

// Load names from text file.


try {
// Load list from named file.
linkedlist.loadFromFile( args[0] );
}
System.out.println( "Couldn't load file: " + args[0] );
System.out.println( e.getMessage() );
System.exit(-2);
}

// Now display contents of linkedlist.


linkedlist.printData( System.out );
}
}

© 2003 SkillBuilders Inc. V 5.4


Introduction to Java Programing: Workshop Solutions Page 42

Chapter 17:
Throwing an Exception Workshop

BigCorpET.java
/*
* BigCorpThrow - Throw an Exception workshop
*/

package com.skillbuilders;
import java.util.*;

public class BigCorpThrow {


public static void main (String[] args) {
Employee [] staff = new Employee[3];

// here's a wage employee


WageEmployee myEmpl1 =
new WageEmployee("john", "Wemployee", "Wage11", 40, 10);
System.out.println("My wage employee is " + myEmpl1.getName()
+ ", id number "
+ myEmpl1.getID());
myEmpl1.talk("I work harder");
myEmpl1.talk();
myEmpl1.personalOpinion();
System.out.println(" ");

// here's a salaried employee -a NEGATIVE Salary - triggers EXCEPTION


SalariedEmployee myEmpl2 =
new SalariedEmployee("Harry", "Salworker", "Sal22", -400 );
System.out.println("My salaried employee is " + myEmpl2.getName()
+ ", id number " + myEmpl2.getID());
System.out.println(myEmpl2.getName() + " will be paid "
+ myEmpl2.getWallet());
myEmpl2.talk("I am the Boss");
myEmpl2.setHeight(76);
System.out.println("this employee is " + myEmpl2.getHeight()
+ " inches tall");
System.out.println(" ");

// here's a Temp employee


TempEmployee myEmpl3 =

© 2003 SkillBuilders Inc. V 5.4


Introduction to Java Programing: Workshop Solutions Page 43

new TempEmployee("Robby", "Constructor", "Tmp33", 300, 55);


System.out.println("My Temp employee is " + myEmpl3.getName()
+ ", id number "
+ myEmpl3.getID());
myEmpl3.talk();
myEmpl3.walk();
System.out.println(" ");

// here's a Client
Client myClient1 = new Client("john", "Constructor", true);
System.out.println("My client is " + myClient1.getName()
+ ", their status is "
+ myClient1.isActive());
myClient1.setActive(false);
System.out.println("Now my client, " + myClient1.getName()
+ ", has status "
+ myClient1.isActive());
// Can't pay them - they're not an EMPLOYEE! ==> myClient1.pay();
myClient1.talk();
myClient1.walk();
System.out.println(" ");

// let's pay the employees


staff[0] = myEmpl1;
staff[1] = myEmpl2;
staff[2] = myEmpl3;

int i;
for (i = 0; i < staff.length; i++) {
staff[i].pay();
System.out.println(staff[i].getName() + " will be paid "
+ staff[i].getWallet());
}
}
}

abstract class Person {

private String lName;


private String fName;
private int height;

private static long population;


private static long totalHeight;
private static float averageHeight;

public Person () {
population++;
}
public Person (String inFName, String inLName) {
this();
setLName(inLName);
setFName(inFName);
}

static long getPopulation () {


return population;
}

© 2003 SkillBuilders Inc. V 5.4


Introduction to Java Programing: Workshop Solutions Page 44

static float getAverageHeight() {


return averageHeight;
}

public void setLName(String inLName) {


lName = inLName;
}
public void setFName(String inFName) {
fName = inFName;
}
public String getLName() {
return lName;
}
public String getFName() {
return fName;
}
public String getName() {
return (fName + " " + lName);
public int getHeight() {
return height;
}
public void setHeight(int inHeight) {
height = inHeight;
totalHeight += height;
setAverageHeight(height);
}

void setAverageHeight(int height) {


if (totalHeight != 0)
averageHeight = (float) totalHeight / population;
else
averageHeight = 0;
}

void walk() {
System.out.println(getFName() + " " + getLName()
+ " is walking");
}

void talk() {
System.out.println(getFName() + " " + getLName()
+ " is talking");
}

void talk(String speech) {


System.out.println(getFName() + " " + getLName()
+ " says: " + speech);
}

public void finalize(){


population --;
totalHeight -= this.height;
setAverageHeight(height);
}
}

abstract class Employee extends Person {

© 2003 SkillBuilders Inc. V 5.4


Introduction to Java Programing: Workshop Solutions Page 45

private String ID;


protected double wallet;

public Employee () {
}

public Employee (String inFName, String inLName, String ID) {


super(inFName, inLName);
this.ID = ID;
}

public String getID() {


return ID;
}
void setID(String ID) {
this.ID = ID;
}
public double getWallet() {
return wallet;
}

abstract void pay(); //abstract method has no body...

public void talk() {


System.out.println("Speaking as an employee");
}
void personalOpinion() {
super.talk();
System.out.println("That is my personal opinion");
}
}

final class Client extends Person {


private boolean active;

public boolean isActive() {


return active;
}
void setActive(boolean active){
this.active = active;
}

public Client (){


}

public Client (String inFName, String inLName, boolean active) {


super(inFName, inLName);
this.active = active;
}
}

final class WageEmployee extends Employee {


private double wage;
private double hours;

public WageEmployee () {
}

© 2003 SkillBuilders Inc. V 5.4


Introduction to Java Programing: Workshop Solutions Page 46

public WageEmployee (String inFName, String inLName,


String ID, double wage, double hours) {
super(inFName, inLName, ID);
this.wage = wage;
this.hours = hours;
}

void pay() {
wallet += (wage * hours);
}
}

final class SalariedEmployee extends Employee {


private double salary;

public SalariedEmployee () {
}

public SalariedEmployee (String inFName, String inLName,


String ID, double salary){
super(inFName, inLName, ID);
if (salary >= 0)
this.salary = salary;
else {
String strMsg = "Salary may not be negative!";
throw new java.lang.IllegalArgumentException(strMsg);
}

void pay() {
wallet = salary;
}
}

private double pay;


private double overtime;

public TempEmployee () {
}

public TempEmployee (String inFName, String inLName,


String ID, double pay, double overtime) {
super(inFName, inLName, ID);
this.pay= pay;
this.overtime = overtime;

void pay() {
wallet = pay + overtime;
}
}

© 2003 SkillBuilders Inc. V 5.4


Introduction to Java Programing: Workshop Solutions Page 47

Chapter 17:
Catching an Exception Workshop

BigCorpCatch.java
/*
* BigCorpCatch - Catch an Exception workshop
*/

package com.skillbuilders;
import java.util.*;

public class BigCorpCatch {


public static void main (String[] args) {
Employee [] staff = new Employee[3];

// here's a wage employee


WageEmployee myEmpl1 =
new WageEmployee("john", "Wemployee", "Wage11", 40, 10);
System.out.println("My wage employee is " + myEmpl1.getName()
+ ", id number "
+ myEmpl1.getID());
myEmpl1.talk("I work harder");
myEmpl1.talk();
myEmpl1.personalOpinion();
System.out.println(" ");
staff[0] = myEmpl1; // add them to the pay table

// here's a salaried employee- a NEGATIVE Salary - triggers EXCEPTION


try {
SalariedEmployee myEmpl2 =
new SalariedEmployee("Harry", "Salworker", "A12345", -400 );
System.out.println("My salaried employee is "
+ myEmpl2.getName()
+ ", id number " + myEmpl2.getID());
myEmpl2.talk("I am the Boss");
myEmpl2.setHeight(76);
System.out.println("this employee is " + myEmpl2.getHeight()
+ " inches tall");
System.out.println(" ");
staff[1] = myEmpl2;
}

© 2003 SkillBuilders Inc. V 5.4


Introduction to Java Programing: Workshop Solutions Page 48

catch(IllegalArgumentException i) {
System.out.println
("My salaried employee had a negative salary");
return;
}

// here's a Temp employee


TempEmployee myEmpl3 =
new TempEmployee("Robby", "Constructor", "Tmp33", 300, 55);
System.out.println("My Temp employee is " + myEmpl3.getName()
+ ", id number "
+ myEmpl3.getID());
myEmpl3.talk();
myEmpl3.walk();
System.out.println(" ");
staff[2] = myEmpl3; //put them in the pay table

// here's a Client
Client myClient1 = new Client("john", "Constructor", true);
System.out.println("My client is " + myClient1.getName()
+ ", their status is "
+ myClient1.isActive());
myClient1.setActive(false);
System.out.println("Now my client, " + myClient1.getName()
+ ", has status "
+ myClient1.isActive());
// Can't pay them - they're not an EMPLOYEE! ==> myClient1.pay();
myClient1.talk();
myClient1.walk();
System.out.println(" ");

// let's pay the employees

int i;
for (i = 0; i < staff.length; i++) {
staff[i].pay();
System.out.println(staff[i].getName() + " will be paid "
+ staff[i].getWallet());
}
}
}

abstract class Person {

private String lName;


private String fName;
private int height;

private static long population;


private static long totalHeight;
private static float averageHeight;

public Person () {
population++;
}
public Person (String inFName, String inLName) {
this();

© 2003 SkillBuilders Inc. V 5.4


Introduction to Java Programing: Workshop Solutions Page 49

setLName(inLName);
setFName(inFName);
}

static long getPopulation () {


return population;
}

static float getAverageHeight() {


return averageHeight;
}

public void setLName(String inLName) {


lName = inLName;
}
public void setFName(String inFName) {
fName = inFName;
}
public String getLName() {
return lName;
}
public String getFName() {
return fName;
}
public String getName() {
return (fName + " " + lName);
}
public int getHeight() {
return height;
}
public void setHeight(int inHeight) {
height = inHeight;
totalHeight += height;
setAverageHeight(height);
}
void setAverageHeight(int height) {
if (totalHeight != 0)
averageHeight = (float) totalHeight / population;
else
averageHeight = 0;
}
void walk() {
System.out.println(getFName() + " " + getLName()
+ " is walking");
}
void talk() {
System.out.println(getFName() + " " + getLName()
+ " is talking");
}
void talk(String speech) {
System.out.println(getFName() + " " + getLName()
+ " says: " + speech);
}
public void finalize(){
population --;
totalHeight -= this.height;
setAverageHeight(height);
}

© 2003 SkillBuilders Inc. V 5.4


Introduction to Java Programing: Workshop Solutions Page 50

abstract class Employee extends Person {


private String ID;
protected double wallet;

public Employee () {
}

public Employee (String inFName, String inLName, String ID) {


super(inFName, inLName);
this.ID = ID;
}

public String getID() {


return ID;
}
void setID(String ID) {
this.ID = ID;
}
public double getWallet() {
return wallet;
}

abstract void pay(); //abstract method has no body...

public void talk() {


System.out.println("Speaking as an employee");
}
void personalOpinion() {
super.talk();
System.out.println("That is my personal opinion");
}
}

final class Client extends Person {


private boolean active;

return active;
}
void setActive(boolean active){
this.active = active;
}

public Client (){


}

public Client (String inFName, String inLName, boolean active) {


super(inFName, inLName);
this.active = active;
}
}

final class WageEmployee extends Employee {


private double wage;
private double hours;

public WageEmployee () {

© 2003 SkillBuilders Inc. V 5.4


Introduction to Java Programing: Workshop Solutions Page 51

public WageEmployee (String inFName, String inLName,


String ID, double wage, double hours) {
super(inFName, inLName, ID);
this.wage = wage;
this.hours = hours;
}

void pay() {
wallet += (wage * hours);
}
}

final class SalariedEmployee extends Employee {


private double salary;

public SalariedEmployee (String inFName, String inLName,


String ID, double salary){
super(inFName, inLName, ID);
if (salary >= 0)
this.salary = salary;
else {
String strMsg = "Salary may not be negative!";
throw new java.lang.IllegalArgumentException(strMsg);
}

void pay() {
wallet = salary;
}
}

final class TempEmployee extends Employee {


private double pay;
private double overtime;

public TempEmployee () {
}

public TempEmployee (String inFName, String inLName,


String ID, double pay, double overtime) {
super(inFName, inLName, ID);
this.pay= pay;
this.overtime = overtime;

void pay() {
wallet = pay + overtime;
}

© 2003 SkillBuilders Inc. V 5.4


Introduction to Java Programing: Workshop Solutions Page 52

Chapter 18:
Multi-Threading Workshop

HelloWorldMT.java
/*
* HelloWorld
*
* Thread exercise: Rainbow background on HelloWorld applet
*/
import java.applet.Applet;
import java.awt.*;
import javax.swing.*;

public class HelloWorldMultiThread extends Applet implements Runnable {


private JLabel label =
new JLabel("Hello World!", JLabel.CENTER);
private int iCounter;

// Initialize Color array; argument is # of shades in


// each phase.
private Color[] clrRainbow = initRainbow(8);
private int iColorIndex = 0;

new JScrollBar(JScrollBar.VERTICAL, 500, 50, 100, 1050);

public void init() {


iCounter ++;
System.out.println("init invoked " + iCounter + " times");

sb.setUnitIncrement(20);
sb.setBlockIncrement(100);

setLayout( new BorderLayout() );


add( BorderLayout.EAST, sb );
add( BorderLayout.NORTH, label );

Thread thr = new Thread(this);


thr.start();
}

public void start() {


System.out.println("start invoked");

© 2003 SkillBuilders Inc. V 5.4


Introduction to Java Programing: Workshop Solutions Page 53

}
public void stop() {
System.out.println("stop invoked");
}
public void destroy() {
System.out.println("destroy invoked");
}

public void run() {


while(true) {
Color cBack = clrRainbow[iColorIndex];
setBackground(cBack);

// Change foreground of label to opposite color.


Color cFore = new Color( 255 - cBack.getRed(),
255 - cBack.getGreen(),
255 - cBack.getBlue() );
label.setForeground( cFore );

iColorIndex = (++iColorIndex % clrRainbow.length);


try {
// Thread.sleep(1000);
int n = sb.getValue();
showStatus( "Sleeping for " + n + " milliseconds" );
Thread.sleep( n );
}
catch(InterruptedException e) {}
}
}
private Color[] initRainbow(int shades) {
// Initialize rainbow array of color objects
Color[] clrRainbow = new Color[3 * shades];
float r = 1.0f, g = 0.0f, b = 0.0f;
final float INCR = 1.0f/shades;
System.out.println( "INCR=" + INCR + "; shades=" + shades);
for( int i = 0; i < shades; i++ ) {
clrRainbow[i] = new Color( r, g, b );
System.out.println( i + ": " + r + ", " + g + ", " + b);
r -= INCR;
g += INCR;
}
for( int i = 0; i < shades; i++ ) {
clrRainbow[i + shades] = new Color( r, g, b );
System.out.println( i + ": " + r + ", " + g + ", " + b);
g -= INCR;
b += INCR;
}
for( int i = 0; i < shades; i++ ) {
clrRainbow[i + 2 * shades] = new Color( r, g, b );
System.out.println( i + ": " + r + ", " + g + ", " + b);
b -= INCR;
r += INCR;
}
return clrRainbow;
}
}

© 2003 SkillBuilders Inc. V 5.4


Introduction to Java Programing: Workshop Solutions Page 54

HelloWorldMT.html
<HTML>
<APPLET CODE="HelloWorldMT.class"
WIDTH=300
HEIGHT=200>
</APPLET>
</HTML>

© 2003 SkillBuilders Inc. V 5.4


Introduction to Java Programing: Workshop Solutions Page 55

Chapter 19:
Swing Containers Workshop

Sampler.java
/*
* Sampler - containers
*/

package mylabs;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class Sampler extends JFrame


implements ActionListener, KeyListener {

private JTextField tfName ;


private JTextField tfPass ;
private JTextArea taAddress ;
private JButton btnOK ;
private JButton btnCancel ;

public Sampler(String title) {


super(title);
setDefaultCloseOperation(EXIT_ON_CLOSE); // Kill app on close
init();
setSize(600, 350);
show();
}

public void init() {


tfName = new JTextField(15);
tfPass = new JTextField(15);
taAddress = new JTextArea("", 10, 20);
btnOK = new JButton("OK");
btnCancel = new JButton("Cancel");

// Create panels
JPanel pnlRed = new JPanel();
JPanel pnlCyan = new JPanel();

© 2003 SkillBuilders Inc. V 5.4


Introduction to Java Programing: Workshop Solutions Page 56

JPanel pnlYellow = new JPanel();


JPanel pnlMain = new JPanel();

// Give buttons mnemonics


btnOK.setMnemonic('O');
btnCancel.setMnemonic('C');

// Set colors
tfName.setBackground( Color.lightGray );
tfName.setForeground( Color.red );
tfPass.setBackground( tfName.getBackground() );
tfPass.setForeground( tfName.getForeground() );
taAddress.setBackground( Color.white );

// Set fonts
tfName.setFont( new Font( "Serif", Font.ITALIC, 20 ));
tfPass.setFont( tfName.getFont() );
taAddress.setFont( new Font( "SansSerif", Font.BOLD, 16 ));

// Put titled border around JTextArea


taAddress.setBorder( BorderFactory.createTitledBorder("Address") );

// Add components to container


// First panel
pnlRed.add(new JLabel("Name:"));
pnlRed.add(tfName);
pnlRed.add(new JLabel("Password:"));
pnlRed.add(tfPass);
pnlRed.setBackground(Color.red);
pnlMain.add(pnlRed); // Add panel to main

// Second panel
// pnlCyan.add(new JLabel("Address:"));
pnlCyan.add(taAddress);
pnlCyan.setBackground(Color.cyan);
pnlMain.add(pnlCyan); // Add panel to main

// Third panel
pnlYellow.add(btnOK);
pnlYellow.add(btnCancel);
pnlYellow.setBackground(Color.yellow);
pnlCyan.add(pnlYellow); // Add 3rd panel to 2nd panel

// Set pnlMain color and assign as content pane


pnlMain.setBackground( Color.white ); // background
setContentPane( pnlMain );

btnOK.setEnabled(false); // OK button starts out disabled.


tfName.requestFocus(); // Start cursor in name field.

// Register listeners
btnOK.addActionListener( this );
btnCancel.addActionListener( this );

tfName.addActionListener( this );
tfPass.addActionListener( this );

tfName.addKeyListener( this );

© 2003 SkillBuilders Inc. V 5.4


Introduction to Java Programing: Workshop Solutions Page 57

tfPass.addKeyListener( this );

// Set font for demo purposes


com.sb.gui.FontSetter.setAppFont(getContentPane());
}

public void actionPerformed( ActionEvent ae ) {


if( ae.getSource() == btnOK ) {
if(tfName.getText().equals("")) {
showStatus("You must enter a name.");
tfName.requestFocus();
}
else
showStatus("Greetings, " + tfName.getText());
}
else if( ae.getSource() == btnCancel ) {
tfName.setText("");
tfPass.setText("");
taAddress.setText("");
showStatus("");
tfName.requestFocus();
btnOK.setEnabled( false );
}
else if(ae.getSource() == tfName)
tfPass.requestFocus();
else if(ae.getSource() == tfPass)
taAddress.requestFocus();
}

public void keyReleased( KeyEvent ke ) {


if(tfName.getText().trim().equals("") ||
tfPass.getText().trim().equals(""))

btnOK.setEnabled( false );
else
btnOK.setEnabled( true );
}

public void keyPressed( KeyEvent ke ) {}


public void keyTyped( KeyEvent ke ) {}

public static void main(String[] args) {


Sampler samp = new Sampler("GUI Sampler");
// Sampler samp = new Sampler();
// samp.setTitle("GUI Sampler");
}

private void showStatus(String text) {


System.out.println(text);
}

© 2003 SkillBuilders Inc. V 5.4


Introduction to Java Programing: Workshop Solutions Page 58

Chapter 20:
Layout Manger Workshop

Sampler.java
/*
* Sampler - Layout Manager
*/

package mylabs;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class Sampler extends JFrame


implements ActionListener, KeyListener {

private JTextField tfName ;


private JTextField tfPass ;
private JTextArea taAddress ;
private JButton btnOK ;
private JButton btnCancel ;

public Sampler(String title) {


super(title);
setDefaultCloseOperation(EXIT_ON_CLOSE); // Kill app on close
init();
setSize(600, 350);
show();
}

public void init() {


tfName = new JTextField(15);
tfPass = new JTextField(15);
taAddress = new JTextArea("", 10, 20);
btnOK = new JButton("OK");
btnCancel = new JButton("Cancel");

// Create panels
JPanel pnlRed = new JPanel();
JPanel pnlCyan = new JPanel();
JPanel pnlYellow = new JPanel();

© 2003 SkillBuilders Inc. V 5.4


Introduction to Java Programing: Workshop Solutions Page 59

JPanel pnlMain = new JPanel();

// Give buttons mnemonics


btnOK.setMnemonic('O');
btnCancel.setMnemonic('C');

// Set colors
tfName.setBackground( Color.lightGray );
tfName.setForeground( Color.red );
tfPass.setBackground( tfName.getBackground() );
tfPass.setForeground( tfName.getForeground() );
taAddress.setBackground( Color.white );

// Set fonts
tfName.setFont( new Font( "Serif", Font.ITALIC, 20 ));
tfPass.setFont( tfName.getFont() );
taAddress.setFont( new Font( "SansSerif", Font.BOLD, 16 ));

// Put titled border around JTextArea


taAddress.setBorder( BorderFactory.createTitledBorder("Address") );

// Add components to container


// First panel
pnlRed.add(new JLabel("Name:"));
pnlRed.add(tfName);
pnlRed.add(new JLabel("Password:"));
pnlRed.add(tfPass);
pnlRed.setBackground(Color.red);
pnlMain.add(pnlRed); // Add panel to main

// Second panel
// pnlCyan.add(new JLabel("Address:"));
pnlCyan.add(taAddress);
pnlCyan.setBackground(Color.cyan);
pnlMain.add(pnlCyan); // Add panel to main

// Third panel
pnlYellow.add(btnOK);
pnlYellow.add(btnCancel);
pnlYellow.setBackground(Color.yellow);
pnlCyan.add(pnlYellow); // Add 3rd panel to 2nd panel

// Set pnlMain color and assign as content pane


pnlMain.setBackground( Color.white ); // background
setContentPane( pnlMain );

btnOK.setEnabled(false); // OK button starts out disabled.


tfName.requestFocus(); // Start cursor in name field.

// Register listeners
btnOK.addActionListener( this );
btnCancel.addActionListener( this );

tfName.addActionListener( this );
tfPass.addActionListener( this );

tfName.addKeyListener( this );
tfPass.addKeyListener( this );

© 2003 SkillBuilders Inc. V 5.4


Introduction to Java Programing: Workshop Solutions Page 60

// Set font for demo purposes


com.sb.gui.FontSetter.setAppFont(getContentPane());
}

public void actionPerformed( ActionEvent ae ) {


if( ae.getSource() == btnOK ) {
if(tfName.getText().equals("")) {
showStatus("You must enter a name.");
tfName.requestFocus();
}
else
showStatus("Greetings, " + tfName.getText());
}
else if( ae.getSource() == btnCancel ) {
tfName.setText("");
tfPass.setText("");
taAddress.setText("");
showStatus("");
tfName.requestFocus();
btnOK.setEnabled( false );
}
else if(ae.getSource() == tfName)
tfPass.requestFocus();
else if(ae.getSource() == tfPass)
taAddress.requestFocus();
}

public void keyReleased( KeyEvent ke ) {


if(tfName.getText().trim().equals("") ||
tfPass.getText().trim().equals(""))

btnOK.setEnabled( false );
else
btnOK.setEnabled( true );
}

public void keyPressed( KeyEvent ke ) {}


public void keyTyped( KeyEvent ke ) {}

public static void main(String[] args) {


Sampler samp = new Sampler("GUI Sampler");
// Sampler samp = new Sampler();
// samp.setTitle("GUI Sampler");
}

private void showStatus(String text) {


System.out.println(text);
}

© 2003 SkillBuilders Inc. V 5.4


Introduction to Java Programing: Workshop Solutions Page 61

Chapter 21:
Windowed Application Workshop

WinApp.java

/*
* WinApp
*
* Windowed application workshop
*/

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class WinApp extends JFrame {


private boolean _bTextChanged;

public static void main( String[] args ) {


new WinApp();
}

private WinApp() { // Constructor


setSize( 400, 200 );
setTitle( "StudentSoft Super System" );

JTextArea ta = new JTextArea();


ta.setLineWrap(true);
ta.setWrapStyleWord(true);
ta.addKeyListener( new KeyHandler() );
getContentPane().add(BorderLayout.CENTER, ta);

// Do nothing on close to allow custom handler to


// control whether window closes or not.
setDefaultCloseOperation( JFrame.DO_NOTHING_ON_CLOSE );

// Register window listener


addWindowListener( new WindowHandler() );

initMenu(); // Create menu

© 2003 SkillBuilders Inc. V 5.4


Introduction to Java Programing: Workshop Solutions Page 62

// Set font for demo purposes


com.sb.gui.FontSetter.setAppFont(this);

show();
}

// Separate method to set up menu:


private void initMenu() {
JMenu mFile = new JMenu("File");
mFile.setMnemonic('F');

JMenuItem miOpen = new JMenuItem("Open");


miOpen.setActionCommand("FileOpen");
miOpen.setMnemonic('O');
mFile.add(miOpen);

JMenuItem miSave = new JMenuItem("Save");


miSave.setActionCommand("FileSave");
miSave.setMnemonic('S');
mFile.add(miSave);

mFile.addSeparator();
JMenuItem miExit = new JMenuItem("Exit");
miExit.setActionCommand("FileExit");
miExit.setMnemonic('x');
mFile.add(miExit);

JMenuBar mb = new JMenuBar();


mb.add(mFile);
setJMenuBar(mb);

// Register menu listeners:


MenuHandler mh = new MenuHandler();
miOpen.addActionListener( mh );
miSave.addActionListener( mh );
miExit.addActionListener( mh );
}

private boolean quit() {


int iAnsw;
boolean bQuit = false, bSave = false;
if( _bTextChanged ) {
iAnsw = JOptionPane.showConfirmDialog( WinApp.this,
"Save changes before quitting?", "Exiting Application",
JOptionPane.YES_NO_CANCEL_OPTION );

bSave = (iAnsw == JOptionPane.YES_OPTION);


bQuit = (iAnsw != JOptionPane.CANCEL_OPTION);
}
else {
iAnsw = JOptionPane.showConfirmDialog( WinApp.this,
"Are you sure you want to quit?", "Exiting Application",
JOptionPane.YES_NO_OPTION );
bQuit = (iAnsw == JOptionPane.YES_OPTION);
}

// If they said to save, do so


if( bSave )

© 2003 SkillBuilders Inc. V 5.4


Introduction to Java Programing: Workshop Solutions Page 63

; // Save here...
// If they said to quit, do so
if( bQuit )
System.exit(0);
return bQuit;
}

private class MenuHandler implements ActionListener {


public void actionPerformed( ActionEvent e ) {
String s = e.getActionCommand();
if( s.equals("FileExit") ) {
quit();
}

else if( s.equals("FileOpen") )


JOptionPane.showMessageDialog( WinApp.this,
"You would open a file here." );

else if( s.equals("FileSave") ) {


JOptionPane.showMessageDialog( WinApp.this,
"File has been saved." );
_bTextChanged = false;
}
} // End of method
} // End of class

private class WindowHandler extends WindowAdapter {


public void windowClosing( WindowEvent e ) {
quit();
}
}

private class KeyHandler extends KeyAdapter {


public void keyReleased( KeyEvent e ) {
_bTextChanged = true; // Text changed
}
}
}

© 2003 SkillBuilders Inc. V 5.4


Introduction to Java Programing: Workshop Solutions Page 64

Chapter 5 Advanced: Creating Classes

Bank.java
package mycode;

import course.bankapp.util.*;

import java.util.*;

public class Bank {

//================================================
// Instance Variables
//================================================

private String strName;


private Account acctCurrent; // The current account.
private Account[] accounts = new Account[10];

//================================================
// Constructors
//================================================

public Bank(String name) {


strName = name;
}

//================================================
// Instance Methods
//================================================

// Various methods...

public AccountValue createAccount(AccountValue values) {


Account acct = new Account(values, this);

// Make the new account current


acctCurrent = acct;

© 2003 SkillBuilders Inc. V 5.4


Introduction to Java Programing: Workshop Solutions Page 65

for( int i = 0; i < accounts.length; i++ ) {


if(accounts[i] == null) {
accounts[i] = acct;
break;
}
}

// Put data into AccountValue and return it


values.load(acct);
return values;
}

public String getName() {


return strName;
}

// More methods...
}

BankApp.java
package mycode;

import course.bankapp.audit.Auditable;
import course.bankapp.util.AccountValue;
import com.sb.application.ApplicationBase;

import java.util.*;

public class BankApp extends ApplicationBase


implements com.sb.gui.mvc.App {

//================================================
// Instance Variables
//================================================

private Bank bank;

//================================================
// Instance methods invoked by GUI
//================================================

public Auditable auditBank() {


return null;
}

public boolean createBank(String name) {


bank = new Bank(name);
return true;
}

// Various methods...

© 2003 SkillBuilders Inc. V 5.4


Introduction to Java Programing: Workshop Solutions Page 66

public String getBankName() {


return bank.getName();
}

// More methods...

} // End of BankApp class

Account.java
package mycode;

import course.bankapp.util.*;

import java.util.*;

public class Account {

//================================================
// Instance Variables
//================================================

private String strNumber, strOwner, strDescription, strType;


private double dBalance;
private Bank bank;

//================================================
// Constructors
//================================================

public Account(AccountValue values, Bank bank) {


strNumber = BankUtil.getNextAccountId();
strOwner = values.getOwner();
strType = values.getType();
setDescription(values.getDescription());
this.bank = bank;
}

//================================================
// Instance Methods
//================================================

public double getBalance() {


return dBalance;
}

public Bank getBank() {


return bank;
}

public String getDescription() {

© 2003 SkillBuilders Inc. V 5.4


Introduction to Java Programing: Workshop Solutions Page 67

return strDescription;
}

public void setDescription(String description) {


strDescription = description;
}

public String getNumber() {


return strNumber;
}

public String getOwner() {


return strOwner;
}

public String getType() {


return strType;
}

public AccountValue credit(double amount) {


dBalance += amount;
System.out.println("Credit performed:\n" + this);
return new AccountValue(this);
}

public AccountValue debit(double amount) {


dBalance -= amount;
return new AccountValue(this);
}

public String getTransactionInfo() {


return "";
}

public String toString() {


return
"Account #" + getNumber() + ", " + getDescription() + '\n' +
"Owner: " + getOwner() + '\n' +
"Balance: " + BankUtil.formatAsCurrency(getBalance());
}
}

© 2003 SkillBuilders Inc. V 5.4


Introduction to Java Programing: Workshop Solutions Page 68

Chapter 7 Advanced: Inheritance

CheckingAccount.java
package mycode;

import course.bankapp.util.*;

public class CheckingAccount extends Account {

//================================================
// Instance Variables
//================================================

private int iCheckNum = 0;

//================================================
// Constructors
//================================================

public CheckingAccount(AccountValue values, Bank bank) {


super(values, bank);
}

//================================================
// Instance Methods
//================================================

public int getLastCheckNumber() {


return iCheckNum;
}

public AccountValue debit(double amount) {

iCheckNum++;
return super.debit(amount);
}

public String getTransactionInfo() {


return "Check # " + getLastCheckNumber();
}
}

© 2003 SkillBuilders Inc. V 5.4


Introduction to Java Programing: Workshop Solutions Page 69

Bank.java
public AccountValue createAccount(AccountValue values) {
Account acct = null;

// Create the new account


if(values.getType().equals("General"))
acct = new Account(values, this);
else if(values.getType().equals("Checking"))
acct = new CheckingAccount(values, this);
else if(values.getType().equals("Savings"))
acct = new SavingsAccount(values, this);

// Make the new account current


acctCurrent = acct;

for( int i = 0; i < accounts.length; i++ ) {


if(accounts[i] == null) {
accounts[i] = acct;
break;
}
}

// Put data into AccountValue and return it


values.load(acct);

return values;
}

SavingsAccount.java
package mycode;

import course.bankapp.util.*;

public class SavingsAccount extends Account {

//================================================
// Instance Variables
//================================================

private float fCurrInterest = 0;

//================================================
// Constructors
//================================================

public SavingsAccount(AccountValue values, Bank bank) {


super(values, bank);
}

//================================================

© 2003 SkillBuilders Inc. V 5.4


Introduction to Java Programing: Workshop Solutions Page 70

// Instance Methods
//================================================

public float getCurrentInterest() {


return fCurrInterest;
}

public AccountValue credit(double amount) {

fCurrInterest = BankUtil.getCurrentInterest();
AccountValue av = super.credit(amount);
return av;
}

public String getTransactionInfo() {


return "Interest rate: " + getCurrentInterest() + "%";
}
}

© 2003 SkillBuilders Inc. V 5.4


Introduction to Java Programing: Workshop Solutions Page 71

Chapter 9 Advanced: Interfaces

Account.java
public class Account implements java.io.Serializable, Auditable {

// Various methods...

//================================================
// Instance Methods related to Auditing
//================================================

public AuditInfo audit() {


return new AuditInfo(this, "Account " +
getNumber() + ", " + getDescription() + ", " +
BankUtil.formatAsCurrency(getBalance()));
}

public Auditable[] getChildren() {


return null;
}

public Auditable getParent() {


return bank;
}
}

Bank.java
public class Bank implements java.io.Serializable, Auditable {

// Various methods...

//================================================
// Instance Methods related to Auditing
//================================================

public AuditInfo audit() {

© 2003 SkillBuilders Inc. V 5.4


Introduction to Java Programing: Workshop Solutions Page 72

return new AuditInfo(this, getName());


}

public Auditable[] getChildren() {


return BankUtil.getAuditables(accounts);
}

public Auditable getParent() {


return null;
}
}

BankApp.java
public Auditable auditBank() {
return bank;
}

© 2003 SkillBuilders Inc. V 5.4


Introduction to Java Programing: Workshop Solutions Page 73

Chapter 15 Advanced:
Using Collections

Account.java
/*
Account.java
*/

package mycode;

import course.bankapp.audit.*;
import course.bankapp.transaction.Transaction;
import course.bankapp.util.*;

import java.util.*;

public class Account implements java.io.Serializable, Auditable {

//================================================
// Instance Variables
//================================================

private String strNumber, strOwner, strDescription, strType;


private double dBalance;
private Bank bank;
private ArrayList alTrans = new ArrayList(); // For transactions

//================================================
// Constructors
//================================================

public Account(AccountValue values, Bank bank) {

strNumber = BankUtil.getNextAccountId();
strOwner = values.getOwner();
strType = values.getType();
setDescription(values.getDescription());
this.bank = bank;

© 2003 SkillBuilders Inc. V 5.4


Introduction to Java Programing: Workshop Solutions Page 74

//================================================
// Instance Methods
//================================================

public double getBalance() {


return dBalance;
}

public Bank getBank() {


return bank;
}

public String getDescription() {


return strDescription;
}

public void setDescription(String description) {


strDescription = description;
}

public String getNumber() {


return strNumber;
}

public String getOwner() {


return strOwner;
}

public String getType() {


return strType;
}

public AccountValue credit(double amount) {


dBalance += amount;
recordTransaction(amount);
return new AccountValue(this);
}

public AccountValue debit(double amount) {


dBalance -= amount;
recordTransaction(-amount);
return new AccountValue(this);
}

© 2003 SkillBuilders Inc. V 5.4


Introduction to Java Programing: Workshop Solutions Page 75

public String getTransactionInfo() {


return "";
}

public Collection getTransactions() {


return alTrans;
}

protected void recordTransaction(double amount) {


Transaction trans =
new Transaction(getNumber(), amount, getTransactionInfo());
alTrans.add(trans);
}

public String toString() {


return
"Account #" + getNumber() + ", " + getDescription() + '\n' +
"Owner: " + getOwner() + '\n' +
"Balance: " + BankUtil.formatAsCurrency(getBalance());
}

//================================================
// Instance Methods related to Auditing
//================================================

public AuditInfo audit() {


return new AuditInfo(this, "Account " +
getNumber() + ", " + getDescription() + ", " +
BankUtil.formatAsCurrency(getBalance()));
}

public Auditable[] getChildren() {


return BankUtil.getAuditables(alTrans.toArray());
}

public Auditable getParent() {


return bank;
}

Bank.java
/*
Bank.java

=====================================
After lab Collections
=====================================

© 2003 SkillBuilders Inc. V 5.4


Introduction to Java Programing: Workshop Solutions Page 76

Consult Javadoc documentation for details on the methods


in this class.
*/

package mycode;

import course.bankapp.audit.*;
import course.bankapp.util.*;

import java.util.*;

public class Bank implements java.io.Serializable, Auditable {

//================================================
// Instance Variables
//================================================

private String strName;


private Account acctCurrent; // The current account.
// private Account[] accounts = new Account[10];
private HashMap hmAccounts = new HashMap();

//================================================
// Constructors
//================================================

public Bank(String name) {


strName = name;
}

//================================================
// Instance Methods
//================================================

public int applyInterest() {


return 0;
}

public void closeCurrentAccount() {


/*
for( int i = 0; i < accounts.length; i++ ) {
if(accounts[i] == acctCurrent) {
accounts[i] = null;
break;
}
}
*/
hmAccounts.remove(acctCurrent.getNumber());
acctCurrent = null;
}

public AccountValue createAccount(AccountValue values) {


Account acct = null;

© 2003 SkillBuilders Inc. V 5.4


Introduction to Java Programing: Workshop Solutions Page 77

// Create the new account


if(values.getType().equals("General"))
acct = new Account(values, this);
else if(values.getType().equals("Checking"))
acct = new CheckingAccount(values, this);
else if(values.getType().equals("Savings"))
acct = new SavingsAccount(values, this);

// Make the new account current


acctCurrent = acct;

// Add new account to Hashmap


hmAccounts.put(acct.getNumber(), acct);
/*
for( int i = 0; i < accounts.length; i++ ) {
if(accounts[i] == null) {
accounts[i] = acct;
break;
}
}
*/

// Put data into AccountValue and return it


values.load(acct);

return values;
}

public AccountValue creditCurrentAccount(double amount) {


AccountValue av = acctCurrent.credit(amount);
return av;
}

public AccountValue debitCurrentAccount(double amount) {


AccountValue av = acctCurrent.debit(amount);
return av;
}

public AccountValue[] getAccountValues() {


Object[] accounts = hmAccounts.values().toArray();
return BankUtil.getAccountValues(accounts);
}

public String getName() {


return strName;
}

public Collection getCurrentAccountTransactions() {


return acctCurrent.getTransactions();
}

© 2003 SkillBuilders Inc. V 5.4


Introduction to Java Programing: Workshop Solutions Page 78

public Collection getAllTransactions() {


ArrayList alTrans = new ArrayList();

// Get iterator of accounts in HashMap


Iterator itr = hmAccounts.values().iterator();
while(itr.hasNext()) {
Account acct = (Account) itr.next();
alTrans.addAll(acct.getTransactions());
}

return alTrans;
}

public AccountValue setCurrentAccount(String number) {


/*
for( int i = 0; i < accounts.length; i++ ) {
if(accounts[i].getNumber().equals(number)) {
acctCurrent = accounts[i];
return new AccountValue(accounts[i]);
}
}
return null;
*/
Account acct = (Account) hmAccounts.get(number);
acctCurrent = acct;
return new AccountValue(acct);
}

public AccountValue updateCurrentAccount(AccountValue av) {


acctCurrent.setDescription(av.getDescription());
return av;
}

//================================================
// Instance Methods related to Auditing
//================================================

public AuditInfo audit() {


return new AuditInfo(this, getName());
}

public Auditable[] getChildren() {


// return BankUtil.getAuditables(accounts);
return BankUtil.getAuditables(hmAccounts.values().toArray());
}

public Auditable getParent() {


return null;
}
}

© 2003 SkillBuilders Inc. V 5.4


Introduction to Java Programing: Workshop Solutions Page 79

BankApp.java
/*
BankApp.java

=====================================
After lab Collections
=====================================

Consult Javadoc documentation for details on the methods


in this class.

*/

package mycode;

import course.bankapp.audit.Auditable;
import course.bankapp.util.AccountValue;
import com.sb.application.ApplicationBase;

import java.util.*;

public class BankApp extends ApplicationBase


implements com.sb.gui.mvc.App {

//================================================
// Instance Variables
//================================================

private Bank bank;

//================================================
// Instance methods invoked by GUI
//================================================

public Auditable auditBank() {


return bank;
}

public boolean createBank(String name) {


bank = new Bank(name);
return true;
}

public void closeCurrentAccount() {


bank.closeCurrentAccount();
}

© 2003 SkillBuilders Inc. V 5.4


Introduction to Java Programing: Workshop Solutions Page 80

public AccountValue createAccount(AccountValue av) {


return bank.createAccount(av);
}

public AccountValue creditCurrentAccount(double amount) {


return bank.creditCurrentAccount(amount);
}

public AccountValue debitCurrentAccount(double amount) {


return bank.debitCurrentAccount(amount);
}

public AccountValue[] getAccountValues() {


return bank.getAccountValues();
}

public Collection getAllTransactions() {


return bank.getAllTransactions();
}

public String getBankName() {


return bank.getName();
}

public Collection getCurrentAccountTransactions() {


return bank.getCurrentAccountTransactions();
}

public void loadData(Bank bank) {


this.bank = bank;
}

public Bank saveData() {


return bank;
}

public AccountValue setCurrentAccount(String number) {


return bank.setCurrentAccount(number);
}

public AccountValue updateCurrentAccount(AccountValue av) {


return bank.updateCurrentAccount(av);
}

} // End of BankApp class

// End of file BankApp.java

CheckingAccount.java
/*
Account.java
*/

© 2003 SkillBuilders Inc. V 5.4


Introduction to Java Programing: Workshop Solutions Page 81

package mycode;

import course.bankapp.util.*;

public class CheckingAccount extends Account {

//================================================
// Instance Variables
//================================================

private int iCheckNum = 0;

//================================================
// Constructors
//================================================

public CheckingAccount(AccountValue values, Bank bank) {


super(values, bank);
}

//================================================
// Instance Methods
//================================================

public int getLastCheckNumber() {


return iCheckNum;
}

public AccountValue debit(double amount) {

iCheckNum++;
return super.debit(amount);
}

public String getTransactionInfo() {


return "Check # " + getLastCheckNumber();
}
}

SavingsAccount.java
/*
Account.java
*/

package mycode;

import course.bankapp.util.*;

public class SavingsAccount extends Account {

//================================================

© 2003 SkillBuilders Inc. V 5.4


Introduction to Java Programing: Workshop Solutions Page 82

// Instance Variables

private float fCurrInterest = 0;

//================================================
// Constructors
//================================================

public SavingsAccount(AccountValue values, Bank bank) {


super(values, bank);
}

//================================================
// Instance Methods
//================================================

public float getCurrentInterest() {


return fCurrInterest;
}

public AccountValue credit(double amount) {

fCurrInterest = BankUtil.getCurrentInterest();
AccountValue av = super.credit(amount);
return av;
}

public String getTransactionInfo() {


return "Interest rate: " + getCurrentInterest() + "%";
}
}

© 2003 SkillBuilders Inc. V 5.4


Introduction to Java Programing: Workshop Solutions Page 83

Chapter 17 Advanced: Exceptions

Account.java
public AccountValue credit(double amount) {
if(amount < 0) {
String strMsg =
"Cannot perform credit; negative amounts not allowed";
throw new IllegalArgumentException(strMsg);
}
dBalance += amount;
recordTransaction(amount);
return new AccountValue(this);
}

public AccountValue debit(double amount)


throws InsufficientFundsException {

// Prevent negative amounts


if(amount < 0) {
String strMsg =
"Cannot perform debit; negative amounts not allowed";
throw new IllegalArgumentException(strMsg);
}

// Prevent overdraft
if(amount > dBalance) {
String strMsg =
"Cannot perform debit; insufficient funds in account";
throw new InsufficientFundsException(getNumber(),
amount - dBalance, strMsg);
}

// Perform debit
dBalance -= amount;
recordTransaction(-amount);
return new AccountValue(this);
}

© 2003 SkillBuilders Inc. V 5.4


Introduction to Java Programing: Workshop Solutions Page 84

InsufficientFundsException.java
package mycode;

public class InsufficientFundsException extends Exception {


private String strAcctNum;
private double dShortfall;

public InsufficientFundsException(String acctNum,


double shortfall, String msg) {

super(msg);
strAcctNum = acctNum;
dShortfall = shortfall;
}

public String getAccountNumber() {


return strAcctNum;
}

public double getShortfall() {


return dShortfall;
}
}

CheckingAccount.java
public AccountValue debit(double amount)
throws InsufficientFundsException {

Bank.java
public AccountValue debitCurrentAccount(double amount)
throws InsufficientFundsException {

BankApp.java
public AccountValue debitCurrentAccount(double amount)
throws InsufficientFundsException {

© 2003 SkillBuilders Inc. V 5.4


Introduction to Java Programing: Workshop Solutions Page 85

Chapter 18 Advanced:
Multi-Threading

BankApp.java
public boolean createBank(String name) {
bank = new Bank(name);
new ApplyInterestThread();
return true;
}

//...

public void loadData(Bank bank) {


this.bank = bank;
new ApplyInterestThread();
}

//...

private class ApplyInterestThread extends Thread {


public ApplyInterestThread() {
start();
}

public void run() {


while(true) {
try {
Thread.sleep(30*1000);
}
catch(InterruptedException e) {
}
int n = bank.applyInterest();
System.out.print(new course.util.TimeStamp());
System.out.print(": Interest applied to ");
System.out.println(n + " accounts");
}
}
}

© 2003 SkillBuilders Inc. V 5.4


Introduction to Java Programing: Workshop Solutions Page 86

SavingsAccount.java
public void applyInterest() {
double dInterest =
BankUtil.calculateInterest(getCurrentInterest(), getBalance());
credit(dInterest);
}

Bank.java
public int applyInterest() {
SavingsAccount[] sa =
BankUtil.getSavingsAccounts(hmAccounts.values().toArray());
for( int i = 0; i < sa.length; i++ )
sa[i].applyInterest();
return sa.length;
}

© 2003 SkillBuilders Inc. V 5.4

You might also like