Java for Mainframe Developers Workshop Solutions
Java for Mainframe Developers: Workshop Solutions
i
Table of Contents
Lesson 1: HelloWorld Workshop .................................................................................................1 Lesson 3: Language Basics Workshop ......................................................................................2 Lesson 4: Process Structures Workshop A ...............................................................................4 Lesson 4: Process Structures Workshop B ...............................................................................5 Lesson 5: Using Objects Workshop............................................................................................6 Lesson 5: More Using ObjectsWorkshop ...................................................................................7 Lesson 6: Creating Classes Workshop A ...................................................................................9 Lesson 6: Create Class Workshop B.........................................................................................10 Lesson 6: Create Class Workshop C.........................................................................................12 Lesson 7: Building Packages......................................................................................................15 Lesson 8: Inheritance Workshop A ............................................................................................18 Lesson 8: Inheritance Workshop B ...........................................................................................21 Lesson 9: Throwing an Exception Workshop ..........................................................................26 Lesson 9: Catching an Exception Workshop ...........................................................................31 Lesson 10: MultiThreading Workshop ......................................................................................36 Appendix A: Java File IO ............................................................................................................37 Appendix A Extra: File IO and Multi-threading.........................................................................41 Appendix B: JDBC Workshop....................................................................................................43
© 2004 SkillBuilders Inc.
V 1.2
Java for Mainframe Developers: Workshop Solutions
1
Lesson 1: HelloWorld Workshop
HelloWorld.java /* * HelloWorld */ public class HelloWorld { public static void main (String[] args) { System.out.println("Hello World!!"); } }
© 2004 SkillBuilders Inc.
V 1.2
Java for Mainframe Developers: Workshop Solutions
2
Lesson 3: Language Basics Workshop
DoArithmetic.java // Do Arithmetic java // This is the solution to the SkillBuilders // Java for Mainframe Programmers Workshop 3 class DoArithmetic { public static void main (String[] args) { //play with maximum values int wholeNum = 9999; long longNum = 999999999; double dblNum = 99999999999999.99; int wholeNumTot = 0; long longNumTot = 0; double dblNumTot = 0; //but the reset numbers to easier values for testing wholeNum = 100; longNum = 2500; dblNum = 15000.45; wholeNumTot = 10; longNumTot = 15; dblNumTot = 25.50; // show each of the numbers to start... System.out.println("whole Num = " + wholeNum); System.out.println("Long Num = " + longNum); System.out.println("Double Num = " + dblNum); // add the numbers and show results wholeNumTot += wholeNum; System.out.println("Whole Num Tot plus whole: " + wholeNumTot); longNumTot += longNum; System.out.println("Long Num Tot plus long: " + longNumTot); dblNumTot += dblNum; System.out.println("Double Num Tot plus dbl: " + dblNumTot); // add literals to numbers and show results wholeNumTot = wholeNum + 250; System.out.println("Whole Num Tot:after adding whole + 250: " + wholeNumTot);
© 2004 SkillBuilders Inc.
V 1.2
Java for Mainframe Developers: Workshop Solutions
3
longNumTot = longNum + 175; System.out.println("Long Num Tot: after long + 175: " + longNumTot); dblNumTot = dblNum + 215; System.out.println("Double Num Tot after dbl + 215: " + dblNumTot); // when do we need casting? longNumTot += wholeNum; System.out.println("Long Num Tot plus whole: " + longNumTot); wholeNumTot += (int)longNum; System.out.println("Whole Num Tot plus long: " + wholeNumTot); wholeNumTot += (int)dblNum; System.out.println("Whole Num Tot plus dbl: " + wholeNumTot); longNumTot += (long) dblNum; System.out.println("Long Num Tot plus dbl: " + longNumTot); dblNumTot += longNum; System.out.println("DBL Num Tot plus long: " + dblNumTot); dblNumTot = dblNum + wholeNum + longNum; System.out.println("Dbl Num Tot plus dbl, long and whole : " + dblNumTot); longNumTot = (long) dblNum + wholeNum + longNum; System.out.println("Long Num Tot plus dbl, long and whole : " + longNumTot); //other calcs longNumTot -= dblNum; System.out.println("Long Num Tot minus dbl: " + longNumTot); dblNumTot = wholeNum * dblNum; System.out.println("Dbl Num Tot product of whole *dbl: " + dblNumTot); longNumTot = ((wholeNum + (long) dblNum + longNum) / 3); System.out.println("LongNumTot with average " + longNumTot);
} }
© 2004 SkillBuilders Inc.
V 1.2
Java for Mainframe Developers: Workshop Solutions
4
Lesson 4: Process Structures Workshop A
Multiplication.java // Multiplication java // This is the solution for the SKillBuilders // Java for Mainframe Programmers Workshop 4A class Multiplication { public static void main (String[] args) { int loopNum; int startNum = 2; int currNum; System.out.println("Starting with the number " + startNum); for (loopNum = startNum; loopNum <= startNum + 19; loopNum++) { currNum = startNum * loopNum; if (currNum < 10) System.out.print(" "); System.out.println(currNum); } }
// Extra space if 1 digit
}
© 2004 SkillBuilders Inc.
V 1.2
Java for Mainframe Developers: Workshop Solutions
5
Lesson 4: Process Structures Workshop B
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]); } } } }
© 2004 SkillBuilders Inc.
V 1.2
Java for Mainframe Developers: Workshop Solutions
6
Lesson 5: 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)); } }
© 2004 SkillBuilders Inc.
V 1.2
Java for Mainframe Developers: Workshop Solutions
7
Lesson 5: More Using ObjectsWorkshop
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();
© 2004 SkillBuilders Inc.
V 1.2
Java for Mainframe Developers: Workshop Solutions
8
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)); } }
© 2004 SkillBuilders Inc.
V 1.2
Java for Mainframe Developers: Workshop Solutions
9
Lesson 6: Creating Classes Workshop A
BigCorpCreateClassA.java /* * BigCorpCreateClassA */ import java.util.*;
- Create Class workshop A
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() + " } public void talk(){ System.out.println(getFName() + " }
{ {
" + getLName() + " is walking"); " + getLName() + " is talking");
}
© 2004 SkillBuilders Inc.
V 1.2
Java for Mainframe Developers: Workshop Solutions
10
Lesson 6: Create Class Workshop B
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 () { population++;
© 2004 SkillBuilders Inc.
V 1.2
Java for Mainframe Developers: Workshop Solutions
11
} 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 --; } }
© 2004 SkillBuilders Inc.
V 1.2
Java for Mainframe Developers: Workshop Solutions
12
Lesson 6: Create Class Workshop C
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(" "); // 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(" ");
© 2004 SkillBuilders Inc.
V 1.2
Java for Mainframe Developers: Workshop Solutions
13
// 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() { 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)
© 2004 SkillBuilders Inc.
V 1.2
Java for Mainframe Developers: Workshop Solutions
14
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); } }
© 2004 SkillBuilders Inc.
V 1.2
Java for Mainframe Developers: Workshop Solutions
15
Lesson 7: Building Packages
Setenv.bat @echo off REM This batch file sets the DOS environment for the course REM Introduction to Java. REM REM To use this file: REM 1. If necessary, edit the assignments in the first section REM to match the actual locations on this installation. REM 2. Each time you open a DOS window, run this batch file. REM -------------------------------------------------REM If necessary, correct these assignments: set COURSE_ROOT=c:\JavaIntro set JAVA_HOME=c:\j2sdk1.4.2 REM set JAVA_HOME=c:\j2sdk1.4.0_01 set CLASSPATH=.;c:\JavaIntro\workshops;c:\JavaIntro\lib\introcourse.jar;c:\JavaIntro \lib\sbcourse.jar REM --------------------------------------------------
REM -------------------------------------------------REM Do not make any changes below this point!!! REM -------------------------------------------------REM Remember previous settings call %COURSE_ROOT%\bat\helper\setenv0.bat set PATH=%COURSE_ROOT%\bat;%JAVA_HOME%\bin;%SB_BASE_PATH% REM Display new settings call %COURSE_ROOT%\bat\helper\setenv9.bat %1
© 2004 SkillBuilders Inc.
V 1.2
Java for Mainframe Developers: Workshop Solutions
16
BigCorpPack.java /* * BigCorpPack - Building Packages */ package com.skillbuilders; import java.util.*; public class BigCorpPack { 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(" "); // 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;
© 2004 SkillBuilders Inc.
V 1.2
Java for Mainframe Developers: Workshop Solutions
17
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; } 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); } }
© 2004 SkillBuilders Inc.
V 1.2
Java for Mainframe Developers: Workshop Solutions
18
Lesson 8: 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(); } }
© 2004 SkillBuilders Inc.
V 1.2
Java for Mainframe Developers: Workshop Solutions
19
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; else averageHeight = 0; } void walk() { System.out.println(getFName() + " " + getLName() + " is walking"); } void talk() { System.out.println(getFName() + " " + getLName() + " is talking");
© 2004 SkillBuilders Inc.
V 1.2
Java for Mainframe Developers: Workshop Solutions
20
} 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"); } }
© 2004 SkillBuilders Inc.
V 1.2
Java for Mainframe Developers: Workshop Solutions
21
Lesson 8: 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() + ", id number " + myEmpl3.getID()); myEmpl3.talk(); myEmpl3.walk();
© 2004 SkillBuilders Inc.
V 1.2
Java for Mainframe Developers: Workshop Solutions
22
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; } public void setLName(String inLName) { lName = inLName; } public void setFName(String inFName) { fName = inFName; } public String getLName() { return lName; }
© 2004 SkillBuilders Inc.
V 1.2
Java for Mainframe Developers: Workshop Solutions
23
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; 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; }
© 2004 SkillBuilders Inc.
V 1.2
Java for Mainframe Developers: Workshop Solutions
abstract void pay();
24
//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) { 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; }
© 2004 SkillBuilders Inc.
V 1.2
Java for Mainframe Developers: Workshop Solutions
25
} 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; } }
© 2004 SkillBuilders Inc.
V 1.2
Java for Mainframe Developers: Workshop Solutions
26
Lesson 9: Throwing an Exception Workshop
BigCorpThrow.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 // He has 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 = new TempEmployee("Robby", "Constructor", "Tmp33", 300, 55); System.out.println("My Temp employee is " + myEmpl3.getName() + ", id number "
© 2004 SkillBuilders Inc.
V 1.2
Java for Mainframe Developers: Workshop Solutions
27
+ 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; } static float getAverageHeight() { return averageHeight; } public void setLName(String inLName) { lName = inLName; } public void setFName(String inFName) { fName = inFName;
© 2004 SkillBuilders Inc.
V 1.2
Java for Mainframe Developers: Workshop Solutions
} public String getLName() return lName; } public String getFName() return fName; } public String getName() return (fName + " " + }
28
{ { { 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; 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) {
© 2004 SkillBuilders Inc.
V 1.2
Java for Mainframe Developers: Workshop Solutions
29
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) { 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)
© 2004 SkillBuilders Inc.
V 1.2
Java for Mainframe Developers: Workshop Solutions
30
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; } }
© 2004 SkillBuilders Inc.
V 1.2
Java for Mainframe Developers: Workshop Solutions
31
Lesson 9: 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 // He has 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; } catch(IllegalArgumentException i) { System.out.println("My salaried employee had a negative salary"); return; }
© 2004 SkillBuilders Inc.
V 1.2
Java for Mainframe Developers: Workshop Solutions
32
// 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(); setLName(inLName); setFName(inFName); }
{
static long getPopulation () { return population; } static float getAverageHeight() { return averageHeight; } public void setLName(String inLName) {
© 2004 SkillBuilders Inc.
V 1.2
Java for Mainframe Developers: Workshop Solutions
33
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; public Employee () { } public Employee (String inFName, String inLName, String ID) { super(inFName, inLName); this.ID = ID; } public String getID() {
© 2004 SkillBuilders Inc.
V 1.2
Java for Mainframe Developers: Workshop Solutions
34
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) { 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 () { }
© 2004 SkillBuilders Inc.
V 1.2
Java for Mainframe Developers: Workshop Solutions
35
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; } }
© 2004 SkillBuilders Inc.
V 1.2
Java for Mainframe Developers: Workshop Solutions
36
Lesson 10: MultiThreading Workshop
CounterW1.java /* * CounterW1 */ class CounterW1 extends Thread { private int iStart = 0; public CounterW1( String name, int start ) { super (name); iStart = start; } public void run() { for( int i = iStart; i > 0; i -= 2 ) { System.out.println(getName() + ": " + i ); Thread.yield(); } System.out.println(getName() + " is done"); } }
CounterUpW1.java /* * CounterUpW1 */ class CounterUpW1{ public static void main( String[] args ) { CounterW1 counter1 = new CounterW1("Counter 1", 15); CounterW1 counter2 = new CounterW1("Counter 2", 14); counter1.start(); counter2.start(); System.out.println( "main() is done" ); } }
© 2004 SkillBuilders Inc.
V 1.2
Java for Mainframe Developers: Workshop Solutions
37
Appendix A: Java File IO
Student.java // this was prepared as part of the solution to Workshop 12 - I/O // Step A - Build Student Class // SkillBuilders Java for the Mainframe Developers course class Student { // instance variables String name; String addr; String eMailAddr; String phone; // constructors public Student (String name, String addr, String eMailAddr, String phone) { this.name = name; this.addr = addr; this.eMailAddr = eMailAddr; this.phone = phone; } public Student() { name = " "; addr = " "; eMailAddr = " " ; phone = " " ; } // getters and setters public void setName(String name) { this.name = name; } public void setAddr(String addr) { this.addr = addr; } public void setEMailAddr(String eMailAddr) { this.eMailAddr = eMailAddr; }
© 2004 SkillBuilders Inc.
V 1.2
Java for Mainframe Developers: Workshop Solutions
38
public void setPhone(String phone) { this.phone = phone; } public String getName() { return name; } public String getAddr() { return addr; } public String getEMailAddr() { return eMailAddr; } public String getPhone() { return phone; } }
WriteBinaryFile.java // Prepared as a solution to Workshop 12 - i/o // Step B - Write to a Binary File // SkillBuilders Java for the Mainframe Developer import java.io.*; public class WriteBinaryFile { public static void main (String[] args) { if (args.length == 4) { try { Student newStudent = new Student(args[0], args[1], args[2], args[3]); System.out.println("Student is " + args[0] + ", " + newStudent.getAddr() + ", " + newStudent.getEMailAddr() + ", " + newStudent.getPhone()); File studentFile = new File ("student.dat"); boolean addToFile = true; DataOutputStream myStudentOut = new DataOutputStream ( new BufferedOutputStream ( new FileOutputStream (studentFile, addToFile))); myStudentOut.writeUTF(newStudent.getName()); myStudentOut.writeUTF(newStudent.getAddr()); myStudentOut.writeUTF(newStudent.getEMailAddr()); myStudentOut.writeUTF(newStudent.getPhone()); myStudentOut.close(); } catch (IOException e) { System.out.println("IO Error for student.dat was " + e); } } // end if } // end main } // end class
© 2004 SkillBuilders Inc.
V 1.2
Java for Mainframe Developers: Workshop Solutions
39
ReadBinaryFile.java // Prepared as a solution to Workshop 12 - I/O // Part C Read BinaryFile // SkillBuilders Java for the Mainframe Developer import java.io.*; public class ReadBinaryFile { public static void main (String[] args) { try { Student newStudent = new Student(); File studentFile = new File ("student.dat"); if (studentFile.exists()) { DataInputStream myStudentIn = new DataInputStream ( new BufferedInputStream ( new FileInputStream (studentFile))); while (myStudentIn.available() > 0) { newStudent.setName(myStudentIn.readUTF()); newStudent.setAddr(myStudentIn.readUTF()); newStudent.setEMailAddr(myStudentIn.readUTF()); newStudent.setPhone(myStudentIn.readUTF()); System.out.println("Student was " + newStudent.getName() + ", " + newStudent.getAddr() + ", " + newStudent.getEMailAddr() + ", " + newStudent.getPhone()); } // end while myStudentIn.close(); } // end if exists } // end try catch (IOException e) { System.out.println("IO Error for student.dat was " + e); } // end catch IOE } // end if } // end main } // end class
ReadWriteFile.java // Prepared as a solution to Workshop 12 - I/O // Part D Read BinaryFile // SkillBuilders Java for the Mainframe Developer import java.io.*; public class ReadWriteFile { public static void main (String[] args) { try { Student newStudent = new Student(); File studentFile = new File ("student.dat"); if (studentFile.exists())
© 2004 SkillBuilders Inc.
V 1.2
Java for Mainframe Developers: Workshop Solutions
40
{ DataInputStream myStudentIn = new DataInputStream ( new BufferedInputStream ( new FileInputStream (studentFile))); File studentText = new File ("student.txt"); boolean addToFile = true; PrintWriter myStudentOut = new PrintWriter ( new BufferedWriter( new FileWriter(studentText, addToFile))); while (myStudentIn.available() > 0) { newStudent.setName(myStudentIn.readUTF()); newStudent.setAddr(myStudentIn.readUTF()); newStudent.setEMailAddr(myStudentIn.readUTF()); newStudent.setPhone(myStudentIn.readUTF()); System.out.println("Student was " + newStudent.getName() + ", " + newStudent.getAddr() + ", " + newStudent.getEMailAddr() + ", " + newStudent.getPhone()); myStudentOut.print(newStudent.getName()); myStudentOut.print(newStudent.getAddr()); myStudentOut.print(newStudent.getEMailAddr()); myStudentOut.println(newStudent.getPhone()); } myStudentIn.close(); myStudentOut.close();
// end while
} // end if exists } // end try catch (IOException e) { System.out.println("IO Error for student.dat was " + e); } // end catch IOE } }
© 2004 SkillBuilders Inc.
// end main // end class
V 1.2
Java for Mainframe Developers: Workshop Solutions
41
Appendix A Extra: File IO and Multi-threading
Note that student.java, student.dat and WriteBinaryFile.java are from Lesson A File I/O are reused for this workshop.
ReadBinaryFileR.java // Prepared as a solution to Workshop 12 - I/O // Part C Read BinaryFile // SkillBuilders Java for the Mainframe Developer import java.io.*; public class ReadBinaryFileR implements Runnable { public void run() { try { Student newStudent = new Student(); File studentFile = new File ("student.dat"); if (studentFile.exists()) { DataInputStream myStudentIn = new DataInputStream ( new BufferedInputStream ( new FileInputStream (studentFile))); while (myStudentIn.available() > 0) { newStudent.setName(myStudentIn.readUTF()); newStudent.setAddr(myStudentIn.readUTF()); newStudent.setEMailAddr(myStudentIn.readUTF()); newStudent.setPhone(myStudentIn.readUTF()); System.out.println("Student was " + newStudent.getName() + ", " + newStudent.getAddr() + ", " + newStudent.getEMailAddr() + ", " + newStudent.getPhone()); } // end while myStudentIn.close(); studentFile.delete(); } // end if exists } // end try catch (IOException e) { System.out.println("IO Error for student.dat was " + e); } // end catch IOE } // end if } // end main } // end class
© 2004 SkillBuilders Inc.
V 1.2
Java for Mainframe Developers: Workshop Solutions
42
RunReadRStepB.java // // // //
RunRead java This is the solution to the SkillBuilders Java for Mainframe Programmers Workshop Multi- Threading this is complete only up to step b of the instructions
class RunReadR { public static void main (String[] args) { ReadBinaryFileR myReader = new ReadBinaryFileR(); Thread myThread = new Thread(myReader); myThread.start(); System.out.println("my main is done - Hello World!!"); } }
RunReadR.java // RunRead java // This is the solution to the SkillBuilders // Java for Mainframe Programmers Workshop Multi- Threading import java.util.*; class RunReadR { public static void main (String[] args) throws InterruptedException Date endDate = new Date(); long endTime = endDate.getTime() + (1 * 60 * 1000); //(current time + 1 minute) while ( currentTime() < endTime) { doRead(); }
{
System.out.println("my main is done - Hello World!!"); } // end main public static long currentTime() { Date currentDate = new Date(); long currentTime = currentDate.getTime(); return currentTime; } // end currentTime public static void doRead() throws InterruptedException long sleepFor = (1 * 60 * 1000 / 2); // (30 seconds) ReadBinaryFileR myReader = new ReadBinaryFileR(); Thread myThread = new Thread(myReader); myThread.start(); System.out.println("Going to sleep"); myThread.sleep(sleepFor);
{
System.out.println("DoRead is done"); } // end doRead }
© 2004 SkillBuilders Inc.
V 1.2
Java for Mainframe Developers: Workshop Solutions
43
Appendix B: JDBC Workshop
Customer.java import java.io.*; class Customer implements Serializable { // instance variables String name; String addr; double purchaseAmt; // constructors public Customer (String inName, String inAddr, double inPurchaseAmt) { name = inName; addr = inAddr; purchaseAmt = inPurchaseAmt; } public Customer () { name = "default"; addr = "default"; purchaseAmt = 0; } // getters and setters public void setName(String inName) { name = inName; } public void setAddr(String inAddr) { addr = inAddr; } public void setPurchaseAmt(double inPurchaseAmt) { purchaseAmt = inPurchaseAmt; } public String getName() { return name; } public String getAddr() { return addr; }
© 2004 SkillBuilders Inc.
V 1.2
Java for Mainframe Developers: Workshop Solutions
44
public double getPurchaseAmt() { return purchaseAmt; } }
DataBaseIO.java import java.sql.*; public class DatabaseIO { public static void main(String args[]) { if (args.length >= 1) { try { // create a customer instance Customer aCustomer = new Customer(); // 1. load the database driver Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); // 2. set up the database for odbc connection to // Access DB called SB Customer and connect String url = "jdbc:odbc:Customer"; String user = "Admin"; String pw = ""; Connection myConnection = DriverManager.getConnection(url, user, pw); // 3. create sql statement Statement mySQL = myConnection.createStatement(); String sqlStmt = "SELECT * FROM Customers WHERE CustName = " + "'" + args[0] + "'"; System.out.println("Custname is " + args[0]); // 4. get result set ResultSet myResult = mySQL.executeQuery(sqlStmt); System.out.println("sqlStmt is " + sqlStmt); while (myResult.next()) { aCustomer.setName(myResult.getString(2)); aCustomer.setAddr(myResult.getString(3)); aCustomer.setPurchaseAmt (myResult.getDouble(4)); System.out.println("the customer, " + aCustomer.getName() + " spent " + aCustomer.getPurchaseAmt()); } //5. lets try an insert double insertAmt = 499.98; String insertAddr = "1 Main St. Anytown, IA, 01224"; sqlStmt = "INSERT INTO Customers (custName, custAddr, purchaseAmt) " + "VALUES ('ANYOLD NAME ', " + "'" + insertAddr + "', " + "'" + insertAmt + "')"; mySQL.executeUpdate(sqlStmt); //6. lets try an update... sqlStmt = "update customers set purchaseAmt = purchaseAmt * 1.085"; mySQL.executeUpdate(sqlStmt); //7. lets try a delete... if (args.length == 2) {
© 2004 SkillBuilders Inc.
V 1.2
Java for Mainframe Developers: Workshop Solutions
45
sqlStmt = "Delete From customers where custName = '" + args[1] + "'"; mySQL.executeUpdate(sqlStmt); } // 8. look at the results and print them out myResult = mySQL.executeQuery("select * from customers order by custName"); while(myResult.next()) { aCustomer.setName(myResult.getString(2)); aCustomer.setAddr(myResult.getString(3)); aCustomer.setPurchaseAmt(myResult.getDouble(4)); System.out.println(aCustomer.getName() + " " + aCustomer.getAddr() + " " + aCustomer.getPurchaseAmt()); } // 6. close em down in the proper order myResult.close(); mySQL.close(); myConnection.close(); } catch (ClassNotFoundException cnf) { System.out.println("Class Not Found " + cnf); } catch (SQLException SQLe) { while (SQLe != null) { System.out.println("SQLException caught " + SQLe); SQLe = SQLe.getNextException(); } } }
// end of if
} //end of main } //end of class
© 2004 SkillBuilders Inc.
V 1.2