Examples for Day4 ************************ // Project CommandLineArgs // Class Test // Initialize a Kid object from // command line information. public class Test { public static void main(String[] args) { Kid kid; String aName; int anId; char aGender; short anAge; aName = args[0]; anId = Integer.parseInt(args[1]); aGender = args[2].charAt(0); anAge = (short) Integer.parseInt(args[3]); kid = new Kid(aName, anId, aGender, anAge); kid.print(); } } // Command Line Arguments: {"Jane", "43543", "F", "9"} //Output: name=Jane id=43543 gender=F age=9 ************************ // Project CommandLineArgs // Class Kid public class Kid { // Private instance variables. private String name; private int id; private char gender; private short age; // Default constructor. public Kid() { // Initialize to default values. name = "Unknown"; id = 99999; gender = 'U'; age = -1; } // Parameterized constructor. public Kid(String aName, int anId, char aGender, int anAge) { // name is not the null string. if (aName.equals("")) name = "Unknown"; else name = aName; // id is between 0 and 99999. if (anId < 0 || anId > 99998) id = 99999; else id = anId; // Gender is 'F', 'M', or 'U'. if (aGender != 'F' && aGender != 'M') gender = 'U'; else gender = aGender; // Age is nonnegative. if (anAge < 0) age = (short) -1; age = (short) anAge; } // Accessor method for name. public String getName() { return name; } // Accessor method for id. public int getId() { return id; } // Accessor method for gender. public char getGender() { return gender; } // Accessor method for age. public short getAge() { return (short) age; } // Mutator method for age. public void hasBirthday() { age++; } // Print method. public void print() { System.out.print("name=" + name + " " ); System.out.print("id=" + id + " " ); System.out.print("gender=" + gender + " "); System.out.println("age=" + age + '\n'); } } ************************ // Project InputFile // Class InputFile // Read numbers from an input file and // print their average. import java.io.*; public class InputFile { // Fill in this path before running application. private static final String PATH = ""; public static void main(String[] args) throws IOException { int number, sum, count; double average; String line; String fileName = PATH + "numbers.txt"; // The FileReader object reads bytes from // an input file. FileReader fr = new FileReader(fileName); // The BufferedReader object breaks up the // input into lines. BufferedReader inFile = new BufferedReader(fr); count = 0; sum = 0; while( (line = inFile.readLine()) != null) { number = Integer.parseInt(line); sum += number; count++; } average = (double) sum / count; System.out.println("The average is " + average + "."); } } // Input file: 43 23 96 38 29 // Output: The average is 45.8. ************************ // Project KidsFromFile // Class Test import java.io.*; public class Test { // Fill in this path before running application. private static final String PATH = ""; public static void main(String[] args) throws IOException { Kid kid[] = new Kid[10]; String fileName, line, aName; int anId, anAge, i, kidCount; char aGender; // Set the filename. fileName = PATH + "kids.txt"; // The FileReader object reads bytes from // an input file. FileReader fr = new FileReader(fileName); // The BufferedReader object breaks up the // input into lines. BufferedReader inFile = new BufferedReader(fr); i = 0; while( (aName = inFile.readLine()) != null) { line = inFile.readLine(); anId = Integer.parseInt(line); line = inFile.readLine(); aGender = line.charAt(0); line = inFile.readLine(); anAge = Integer.parseInt(line); kid[i] = new Kid(aName, anId, aGender, anAge); i++; } kidCount = i; // Print Kid objects. for(i = 0; i < kidCount && kid[i] != null; i++) kid[i].print(); } } //Input file: Jessica 37463 F 9 Kevin 55986 M 10 Katie 86372 F 11 William 46347 M 10 //Output: name=Jessica id=37463 gender=F age=9 name=Kevin id=55986 gender=M age=10 name=Katie id=86372 gender=F age=11 name=William id=46347 gender=M age=10 ************************ // Project KidsFile // Class Kids The source code for this class is the same as the Kid1 and CommandLineArgs as given earlier. ************************ // Project StaffMember // Class Main public class Main { public static void main(String[] args) { // Create and populate staff information. Staff personel = new Staff(); // List information about personel // at payday. personel.payDay(); } } //Output: Name=Barb Address=329 Elm St. Phone=453-3837 Thank you. Name=Dennis Address=438 Pine St. Phone=837-2273 Amount paid: $576.85 Name=Norm Address=34 Washington Blvd. Phone=423-2928 Amount paid: $365.75 Name=Susan Address=249 Congress Ave. Phone=473-3339 Amount paid: $1575.95 ************************ // Project StaffMember // Class Staff // Populate Staff object with staff member information. public class Staff { // Instance variable. StaffMember[] staffList; // Populate staffList with objects containing // staff information. public Staff() { staffList = new StaffMember[4]; staffList[0] = new Volunteer( "Barb", "329 Elm St.", "453-3837"); staffList[1] = new Employee( "Dennis", "438 Pine St.", "837-2273", "365-27-2928", 576.85); staffList[2] = new Hourly( "Norm", "34 Washington Blvd.", "423-2928", "243-45-3938", 10.45); staffList[3] = new Executive( "Susan", "249 Congress Ave.", "473-3339", "947-38-2380", 1075.95); ((Hourly) staffList[2]).addHours(35); ((Executive) staffList[3]).setBonus(500.00); } // Display staff information at payday. public void payDay() { int i; double payAmount; for(i = 0; i < staffList.length; i++) { System.out.println(staffList[i]); payAmount = staffList[i].pay(); if (payAmount == 0.0) System.out.println("Thank you."); else System.out.println("Amount paid: $" + payAmount); System.out.println(); } } } ************************ // Project StaffMember // Class StaffMember // The class is abstract because the pay // method must be overridden. public abstract class StaffMember { // Instance variables. private String name; private String address; private String phone; // Constructor for staff member. public StaffMember(String aName, String anAddress, String aPhone) { name = aName; address = anAddress; phone = aPhone; } // Print staff member information. public String toString() { return "Name=" + name + '\n' + "Address=" + address + '\n' + "Phone=" + phone; } // Abstract pay method to be overridden by // classes that inherit StaffMember. public abstract double pay(); } ************************ // Project StaffMember // Class Volunteer public class Volunteer extends StaffMember { // Constructor for volunteer. public Volunteer(String aName, String anAddress, String aPhone) { super(aName, anAddress, aPhone); } // A volunteer does not get paid. public double pay() { return 0.0; } } ************************ // Project StaffMember // Class Employee // Holds information about employee and lets // employee get paid. public class Employee extends StaffMember { // Instance variable. private String SSN; protected double payRate; // Constructor for employee. public Employee(String aName, String anAddress, String aPhone, String anSSN, double aPayRate) { super(aName, anAddress, aPhone); SSN = anSSN; payRate = aPayRate; } // An employee gets paid the monthly pay rate. public double pay() { return payRate; } } ************************ // Project StaffMember // Class Hourly public class Hourly extends Employee { // Instance variable. public int hoursWorked; // Constructor for hourly employee. public Hourly(String aName, String anAddress, String aPhone, String anSSN, double aPayRate) { super(aName, anAddress, aPhone, anSSN, aPayRate); hoursWorked = 0; } // Add more hours to the number of hours the // hourly employee has worked. public void addHours(int moreHours) { hoursWorked += moreHours; } // Pay for hourly employee is hours worked // times pay rate. public double pay() { return hoursWorked * payRate; } } ************************ // Project StaffMember // Class Executive // An executive gets his or her normal salary plus // a monthly bonus. public class Executive extends Employee { // Instance variable. protected double bonus; // Constructor for executive. public Executive(String aName, String anAddress, String aPhone, String anSSN, double aPayRate) { super(aName, anAddress, aPhone, anSSN, aPayRate); bonus = 0; } // Set bonus for executive. public void setBonus(double aBonus) { bonus = aBonus; } // Pay for executive is normal salary plus bonus. public double pay() { return payRate + bonus; } } ************************ // Project Celest // Class Test // Create objects containing information about // celestial objects. import java.util.StringTokenizer; import java.io.*; public class Test { // Fill this path in before compiling. private static final String PATH = ""; public static void main(String[] args) throws IOException { int i, n; String ctype, line, dummy; Celest[] p = new Celest[20]; FileReader fr = new FileReader(PATH + "celest.txt"); BufferedReader inFile = new BufferedReader(fr); StringTokenizer st; for(i = 0; (ctype = inFile.readLine()) != null; i++) { if(ctype.equals("Celest")) p[i] = new Celest(); else if(ctype.equals("Fixed")) p[i] = new Fixed(); else if(ctype.equals("Star")) p[i] = new Star(); else if(ctype.equals("Nebula")) p[i] = new Nebula(); else if(ctype.equals("Planet")) p[i] = new Planet(); p[i].load(inFile); dummy = inFile.readLine(); } n = i; for(i = 0; i < n; i++) p[i].display(); } } //Input File: Nebula NGC224 Andromeda Galaxy 3.4 And 178 S Planet MARS The Red Planet 1.524 0.093 686.98 24.6 2 PHOBOS Mars' smaller moon DEIMOS Mars' larger moon Star BETELGEUSE A red giant -5.5 Ori 150 0.03 Planet JUPITER The king of the planets 5.203 0.048 4333.0 9.84 15 METIS J16 ANDRASTEA J14 ALMATHEA J5 IO J1 EUROPA J2 GANYMEDE J3 CALLISTO J4 LEDA J13 HIMALIA J6 LYSITHEA J10 ELARA J7 ANANKE J12 CARME J11 PASIPHAE J8 SINOPE J9 Star SIRIUS The Dog Star 1.4 CMa 2.7 1.32 Nebula NG1952 Crab Nebula 8.4 Tau 6 Di //Output: NGC224 Andromeda Galaxy Magnitude: 3.4 Constellation: And Size in minutes of arc: 178.0 Type of nebula: S MARS The Red Planet Distance from sun (AU): 0.0 Period of revolution: 686.98 Rotational period: 24.6 Moon #1:PHOBOS Mars' smaller moon Moon #2:DEIMOS Mars' larger moon BETELGEUSE A red giant Magnitude: -5.5 Constellation: Ori Distance from sun (parsecs): 150.0 Motion (seconds per year): 0.03 JUPITER The king of the planets Distance from sun (AU): 0.0 Period of revolution: 4333.0 Rotational period: 9.84 Moon #1:METIS J16 Moon #2:ANDRASTEA J14 Moon #3:ALMATHEA J5 Moon #4:IO J1 Moon #5:EUROPA J2 Moon #6:GANYMEDE J3 Moon #7:CALLISTO J4 Moon #8:LEDA J13 Moon #9:HIMALIA J6 Moon #10:LYSITHEA J10 Moon #11:ELARA J7 Moon #12:ANANKE J12 Moon #13:CARME J11 Moon #14:PASIPHAE J8 Moon #15:SINOPE J9 SIRIUS The Dog Star Magnitude: 1.4 Constellation: CMa Distance from sun (parsecs): 2.7 Motion (seconds per year): 1.32 NG1952 Crab Nebula Magnitude: 8.4 Constellation: Tau Size in minutes of arc: 6.0 Type of nebula: Di ************************ // Project Celest // Class Celest // The Celest class is the parent class for // all of the celestial object classes. import java.util.StringTokenizer; import java.io.*; public class Celest { private String name; private String notes; public void load(BufferedReader in) throws IOException { String line; line = in.readLine(); StringTokenizer st = new StringTokenizer(line); name = st.nextToken(" "); notes = st.nextToken("\n"); } public void display() { System.out.println(name + " " + notes); } } ************************ // Project Celest // Class Fixed // A fixed object is an object that does not // move in the sky, relative to the stars. // Fixed objects are nebula and stars. import java.util.StringTokenizer; import java.io.*; public class Fixed extends Celest { private double magnitude; private String constellation; public void load(BufferedReader in) throws IOException { String line; super.load(in); line = in.readLine(); magnitude = Double.parseDouble(line); line = in.readLine(); constellation = line; } public void display() { super.display(); System.out.println("Magnitude: " + magnitude); System.out.println("Constellation: " + constellation); } } ************************ // Project Celest // Class Nebula // A nebula is a galaxy or luminous gas region. import java.util.StringTokenizer; import java.io.*; public class Nebula extends Fixed { private double size; private String type; public void load(BufferedReader in) throws IOException { String line; super.load(in); line = in.readLine(); size = Double.parseDouble(line); type = in.readLine(); } public void display() { super.display(); System.out.println( "Size in minutes of arc: " + size); System.out.println( "Type of nebula: " + type); System.out.println(); } } ************************ // Project Celest // Class Star // A star is a fixed object. import java.util.StringTokenizer; import java.io.*; public class Star extends Fixed { private double distance; private double properMotion; public void load(BufferedReader in) throws IOException { String line; super.load(in); line = in.readLine(); distance = Double.parseDouble(line); line = in.readLine(); properMotion = Double.parseDouble(line); } public void display() { super.display(); System.out.println( "Distance from sun (parsecs): " + distance); System.out.println( "Motion (seconds per year): " + properMotion); System.out.println(); } } ************************ // Project Celest // Class Planet // A planet is not a fixed object because // it orbits the sun. import java.util.StringTokenizer; import java.io.*; public class Planet extends Celest { double distance; double radius; double eccentricity; double revPeriod; double rotPeriod; int numbMoons; Celest[] moon; public void load(BufferedReader in) throws IOException { String line; int i; super.load(in); line = in.readLine(); radius = Double.parseDouble(line); line = in.readLine(); eccentricity = Double.parseDouble(line); line = in.readLine(); revPeriod = Double.parseDouble(line); line = in.readLine(); rotPeriod = Double.parseDouble(line); line = in.readLine(); numbMoons = Integer.parseInt(line); moon = new Celest[numbMoons]; for(i=0; i< numbMoons; i++) { moon[i] = new Celest(); moon[i].load(in); } } public void display() { int i; super.display(); System.out.println( "Distance from sun (AU): " + distance); System.out.println( "Period of revolution: " + revPeriod); System.out.println( "Rotational period: " + rotPeriod); for(i=0; i< numbMoons; i++) { System.out.print("Moon #" + (i+1) + ":"); moon[i].display(); } System.out.println(); } } ************************ // Project Interface // Class Test // Test the Philosopher and Dog classes which // each implement the Speaker interface. public class Test { public static void main(String[] args) { Philosopher x = new Philosopher("I think, therefore I am."); Dog y = new Dog(); x.speak(); y.speak(); x.announce("To be, or not to be, that is " + "the question."); y.announce("Its a dog's life."); x.pontificate(); System.out.println(); Speaker[] z = new Speaker[2]; z[0] = x; z[1] = y; z[0].speak(); z[1].speak(); ((Philosopher) z[0]).pontificate(); } } //Output: I think, therefore I am.woofTo be, or not to be, that is the question.woof: Its a dog's life.I think, therefore I am.I think, therefore I am.I think, therefore I am.I think, therefore I am.I think, therefore I am.I think, therefore I am.woofI think, therefore I am.I think, therefore I am.I think, therefore I am.I think, therefore I am.I think, therefore I am. ************************ // Project Interface // Interface Speaker // Any class that implements this interface // must provide implementations for the // speak and announce methods. public interface Speaker { public void speak(); public void announce(String str); } ************************ // Project Interface // Class Philospher public class Philosopher implements Speaker { private String philosophy; public Philosopher(String aPhilosophy) { philosophy = aPhilosophy; } public void speak() { System.out.println(philosophy); } public void announce(String announcement) { System.out.println(announcement); } public void pontificate() { int i; for(i = 1; i <=5; i++) System.out.println(philosophy); } } ************************ // Project Interface // Class Dog public class Dog implements Speaker { public void speak() { System.out.println("woof"); } public void announce(String announcement) { System.out.println("woof: " + announcement); } } ************************