22
Homework 4 Enrique Carbajal Jr Points: 80 points possible Part 1: 10 points Test the time Part 2: 10 points Complex Number Part 3: 10 points Payroll System Test Part 4: 10 points Student hierarchy Part 5: 20 points Payroll Modification for $100 bonus Part 6: 20 points ShapesTest Part 1: Test2.java // Lab 1: Time2.java // Time2 class definition with methods tick, // incrementMinute and incrementHour. // Enrique Carbajal public class Time2 { private int hour; // 0 - 23 private int minute; // 0 - 59 private int second; // 0 - 59 // Time2 no-argument constructor: initializes each instance variable // to zero; ensures that Time2 objects start in a consistent state public Time2() { this( 0, 0, 0 ); // invoke Time2 constructor with three arguments } // end Time2 no-argument constructor // Time2 constructor: hour supplied, minute and second defaulted to 0 public Time2( int h ) { this( h, 0, 0 ); // invoke Time2 constructor with three arguments } // end Time2 one-argument constructor // Time2 constructor: hour and minute supplied, second defaulted to 0 public Time2( int h, int m ) { this( h, m, 0 ); // invoke Time2 constructor with three arguments } // end Time2 two-argument constructor // Time2 constructor: hour, minute and second supplied public Time2( int h, int m, int s ) { setTime( h, m, s ); // invoke setTime to validate time } // end Time2 three-argument constructor

Homework 4 Enrique Carbajal Jr - CSUSB

  • Upload
    others

  • View
    2

  • Download
    0

Embed Size (px)

Citation preview

Homework 4Enrique Carbajal Jr

Points: 80 points possible

Part 1: 10 points Test the timePart 2: 10 points Complex NumberPart 3: 10 points Payroll System TestPart 4: 10 points Student hierarchy Part 5: 20 points Payroll Modification for $100 bonusPart 6: 20 points ShapesTest

Part 1: Test2.java// Lab 1: Time2.java// Time2 class definition with methods tick, // incrementMinute and incrementHour.// Enrique Carbajal

public class Time2{ private int hour; // 0 - 23 private int minute; // 0 - 59 private int second; // 0 - 59

// Time2 no-argument constructor: initializes each instance variable // to zero; ensures that Time2 objects start in a consistent state public Time2() { this( 0, 0, 0 ); // invoke Time2 constructor with three arguments } // end Time2 no-argument constructor

// Time2 constructor: hour supplied, minute and second defaulted to 0 public Time2( int h ) { this( h, 0, 0 ); // invoke Time2 constructor with three arguments } // end Time2 one-argument constructor

// Time2 constructor: hour and minute supplied, second defaulted to 0 public Time2( int h, int m ) { this( h, m, 0 ); // invoke Time2 constructor with three arguments } // end Time2 two-argument constructor

// Time2 constructor: hour, minute and second supplied public Time2( int h, int m, int s ) { setTime( h, m, s ); // invoke setTime to validate time } // end Time2 three-argument constructor

// Time2 constructor: another Time2 object supplied public Time2( Time2 time ) { // invoke Time2 constructor with three arguments this( time.getHour(), time.getMinute(), time.getSecond() ); } // end Time2 constructor with Time2 argument

// Set a new time value using universal time. Perform // validity checks on data. Set invalid values to zero. public void setTime( int h, int m, int s) { if( (h >0 && h < 24) && ( m > 0 && m < 60) && (s > 0 && s <60) ) { hour = h; minute = m; second = s; } else { hour = 0; minute = 0; second = 0; } }// End setTime Method {

/* Write code here that declares three boolean variables which are initialized to the return values of setHour, setMinute and setSecond. These lines of code should also set the three member variables. */

/* Return true if all three variables are true; otherwise, return false. */ boolean hourBool ; boolean minuteBool; boolean secondBool;

}

// validate and set hour public void setHour( int newhour) { if (newhour > 0 & newhour <23)

{ hour = newhour; } else { System.out.println("Hour cannot be set"); } }

// validate and set minute public void setMinute( int newminute) { /* Write code here that determines whether the minute is valid. If so, set the minute and return true. */

if ( newminute > 0 & newminute <60) {

minute = newminute; } else

System.out.println("The ninutes are not correct"); }//End set minute method

public void setSecond(int newsecond) {

if (newsecond > 0 && newsecond <60) {

second = newsecond; } else

System.out.println("Please enter a correct seconds"); }

// Get Methods // get hour value public int getHour() { return hour; } // end method getHour

// get minute value public int getMinute() { return minute; } // end method getMinute

// get second value public int getSecond() { return second; } // end method getSecond

// Tick the time by one second public void tick() { setSecond( second + 1 );

if ( second == 0 ) incrementMinute(); } // end method tick

// Increment the minute public void incrementMinute() { setMinute( minute + 1 );

if ( minute == 0 ) incrementHour(); } // end method incrementMinute

// Increment the hour public void incrementHour() { setHour( hour + 1 ); } // end method incrementHour // convert to String in universal-time format (HH:MM:SS) public String toUniversalString() { return String.format( "%02d:%02d:%02d", getHour(), getMinute(), getSecond() ); } // end method toUniversalString

// convert to String in standard-time format (H:MM:SS AM or PM) public String toString() { return String.format( "%d:%02d:%02d %s", ( ( getHour() == 0 || getHour() == 12 ) ? 12 : getHour() % 12 ), getMinute(), getSecond(), ( getHour() < 12 ? "AM" : "PM" ) ); } // end method toStandardString} // end class Time2

I completed writing the methods for all the Time2.java class. I also completed writing the methods for the Time2Test.java

Part 1 Time2Test.java// Lab 1: Time2Test.java// Program adds validation to Fig. 8.7 exampleimport java.util.Scanner;

public class Time2Test{ public static void main( String args[] ) { Scanner input = new Scanner( System.in );

Time2 time = new Time2(); // the Time2 object

int choice = getMenuChoice(); while ( choice != 5 ) { switch ( choice ) { case 1: // set hour System.out.print( "Enter Hours: " ); int hours = input.nextInt(); time.setHour(hours); break; case 2: // set minute System.out.print( "Enter Minutes: " ); int minutes = input.nextInt(); time.setMinute(minutes); break; case 3: // set seconds System.out.print( "Enter Seconds: " ); int seconds = input.nextInt(); time.setSecond(seconds); break; case 4: // add 1 second time.tick(); break; } // end switch System.out.printf( "Hour: %d Minute: %d Second: %d\n", time.getHour(), time.getMinute(), time.getSecond() ); System.out.printf( "Universal time: %s Standard time: %s\n", time.toUniversalString(), time.toString() );

choice = getMenuChoice(); } // end while } // end main

// prints a menu and returns a value corresponding to the menu choice private static int getMenuChoice() { Scanner input = new Scanner( System.in ); System.out.println( "1. Set Hour" ); System.out.println( "2. Set Minute" ); System.out.println( "3. Set Second" ); System.out.println( "4. Add 1 second" ); System.out.println( "5. Exit" ); System.out.print( "Choice: " );

return input.nextInt(); } // end method getMenuChoice} // end class Time2Test

Here is the program running with the user entering information that does not fit into the program and the program telling the user that the hour cannot be set. I gave myself ten points for being able to complete the entire program and have it run correctly.

Part 2: Complex.java// Lab 3: Complex.java// Definition of class Complex

public class Complex{ private double real; private double imaginary;

// Initialize both parts to 0 public Complex() {

real = 0;

imaginary = 0; } // end Complex no-argument constructor

// Initialize real part to r and imaginary part to i public Complex( double realPart , double imaginaryPart) {

real = realPart; imaginary = imaginaryPart;

}// End of two argument constructor

// Add two Complex numbers public Complex add( Complex right ) {

Complex temp = new Complex( this.real, this.imaginary); temp.real = this.real + right.real;

temp.imaginary = this.imaginary + right.imaginary; return temp;

}

// Subtract two Complex numbers public Complex subtract( Complex right ) {

Complex temp = new Complex( this.real, this.imaginary); temp.real = temp.real - right.real; temp.imaginary = temp.imaginary - right.imaginary; return temp;

}

// Return String representation of a Complex number public String toString() { return String.format( "(%.1f, %.1f)", real, imaginary ); } // end method toComplexString;} // end class Complex

//Use this pointers so that you can get the values of the object which you are trying to //add and subtract to. This is the point of this exercise.

Here is the program running.

I gave myself ten points out of ten for being able to write this entire program and having it run correctly.

Part 3: Payroll System TestPart A: The code for the pieceworker// Lab Exercise 1: PieceWorker.java// PieceWorker class extends Employee.

public class PieceWorker extends Employee { private double wage; private double pieces; // five-argument constructor public PieceWorker( String first, String last, String ssn, double wagePerPiece, double piecesProduced ) {

super( first, last, ssn); // Sends to superclass constructor setWage( wagePerPiece); // Sets wage per piece setPieces( piecesProduced);

} // end five-argument PieceWorker constructor

public void setWage(double wagedWork) {

wage = wagedWork; }// Sets the workers wage public double getWage() {

return wage; } // return wage // set pieces produced public void setPieces( double piecesMade) {

pieces = piecesMade; }// Set the amount of pieces produced public double getPieces() {

return pieces; }// Return pieces made // calculate earnings; override abstract method earnings in Employee public double earnings() {

return getWage() * getPieces(); } // end method earnings

// return String representation of PieceWorker object public String toString() {

return String.format( "%s: %s\n%s: $%,.2f\n%s: %.2f", "Piecework Employee", super.toString(),"Wage is", getWage(), "Number of pieces", getPieces(), earnings() ); //Conversion character f will print at least one number to the right of the

decimal //Make sure the formating is the exact way you want it //The spaces in the formatting will effect the way it prints out

} // end method toString} // end class PieceWorker

Part B: PayrollSystemTest.java Here is the code that test the pieceworker class along with all the other classes

// Lab Exercise 1: PayrollSystemTest.java// Employee hierarchy test program.

public class PayrollSystemTest { public static void main( String args[] ) { // create five-element Employee array Employee employees[] = new Employee[ 5 ];

// initialize array with Employees employees[ 0 ] = new SalariedEmployee( "John", "Smith", "111-11-1111", 800.00 ); employees[ 1 ] = new HourlyEmployee( "Karen", "Price", "222-22-2222", 16.75, 40 ); employees[ 2 ] = new CommissionEmployee( "Sue", "Jones", "333-33-3333", 10000, .06 ); employees[ 3 ] = new BasePlusCommissionEmployee( "Bob", "Lewis", "444-44-4444", 5000, .04, 300 ); /* create a PieceWoker object and assign it to employees[ 4 ] */ employees[ 4 ] = new PieceWorker( "Enrique" , "Carbajal Jr", "555-55-5555", 99.99, 237);

System.out.println( "Employees processed polymorphically:\n" ); // generically process each element in array employees for ( Employee currentEmployee : employees ) { System.out.println( currentEmployee ); // invokes toString System.out.printf( "earned $%,.2f\n\n", currentEmployee.earnings() ); } // end for } // end main} // end class PayrollSystemTestHere is the output of the program PayrollSystemTest

I completed all parts of this section and have a working program. I gave myself ten points.

Part 4: Student Hierarchy

Student

Freshman Sophomore Junior Senior

Undergraduate Graduate

Masters

Doctoral

The relationship that exists between these classes is an is-a relationship. For example, Doctoral student is a student. The doctoral student would inherit all the properties of Master’s student and of Undergraduate student along with all the properties of Student. In addition, for example, you could take a sophomore and follow up the hierarchy. A sophomore is an undergraduate which is a student. Inheritance makes it easy for someone to extend an idea further. This saves a lot of time coding and a lot of time developing new methods for things that are already created. The take away from this exercise is that programmers don’t need to reinvent the wheel every time they are programming a new software package.

Part 5: Payroll System Mod. package Part5;

import java.util.Scanner;

// Lab Exercise 1: PayrollSystemTest.java// Employee hierarchy test program.

public class PayrollSystemTest { public static void main( String args[] ) {

Scanner input = new Scanner( System.in); System.out.println("Please enter today's date"); Date today = new Date( input.nextInt(), input.nextInt(), input.nextInt()); System.out.printf("Today's date is %s" , today); System.out.println();

// create five-element Employee array Employee employees[] = new Employee[ 5 ];

// initialize array with Employees employees[ 0 ] = new SalariedEmployee( "John", "Smith", "111-11-1111", new Date (12, 4, 1944), 800.00); employees[ 1 ] = new HourlyEmployee( "Karen", "Price", "222-22-2222", new Date ( 11, 11, 1911), 16.75, 40 ); employees[ 2 ] = new CommissionEmployee( "Sue", "Jones", "333-33-3333", new Date ( 03, 14, 1986), 10000, .06 ); employees[ 3 ] = new BasePlusCommissionEmployee( "Bob", "Lewis", "444-44-4444", new Date(01, 22, 1985 ), 5000, .04, 300 ); /* create a PieceWoker object and assign it to employees[ 4 ] */ employees[ 4 ] = new PieceWorker( "Enrique" , "Carbajal Jr", "555-55-5555", new Date (12, 03, 1950), 203.978, 237);

System.out.println(); System.out.println( "Employees processed polymorphically:\n" );

// generically process each element in array employees for ( Employee currentEmployee : employees ) // Evaluated right to left. The element on the left is an element of the type of the data structure on the right. { System.out.println( currentEmployee ); // invokes toString System.out.printf( "earned $%,.2f\n\n", currentEmployee.earnings() ); if (currentEmployee.getBirthDate().getMonth() == today.getMonth() ) { currentEmployee.earned = currentEmployee.setbonus(); System.out.printf("%s %s\nHappy Birthday!!! You get a $100 bonus\n" , currentEmployee.getFirstName() , currentEmployee.getLastName()); System.out.println(); } } // end for } // end main} // end class PayrollSystemTest

Modified Employee class to include birthdate and bonuspackage Part5;// Lab Exercise 1: Employee.java// Employee abstract superclass.

public abstract class Employee { private String firstName; private String lastName; private String socialSecurityNumber; private Date birthDate; protected double earned;

// three-argument constructor public Employee( String first, String last, String ssn , Date bday) { firstName = first; lastName = last; socialSecurityNumber = ssn; birthDate = bday; } // end four-argument constructor

// set first name public void setFirstName( String first ) { firstName = first; } // end method setFirstName

// return first name public String getFirstName()

{ return firstName; } // end method getFirstName

// set last name public void setLastName( String last ) { lastName = last; } // end method setLastName

// return last name public String getLastName() { return lastName; } // end method getLastName

// set social security number public void setSocialSecurityNumber( String ssn ) { socialSecurityNumber = ssn; // should validate } // end method setSocialSecurityNumber

// return social security number public String getSocialSecurityNumber() { return socialSecurityNumber; } // end method getSocialSecurityNumber public void setBirthDate( Date newbday) {

birthDate = newbday; } public Date getBirthDate() {

return birthDate; }

// return String representation of Employee object public String toString() { return String.format( "%s %s\nsocial security number: %s\n%s", getFirstName(), getLastName(), getSocialSecurityNumber(), getBirthDate() ); } // end method toString

// abstract method overridden by subclasses public abstract double earnings(); // no implementation here // end abstract class Employee public abstract double getearnings(); public abstract double setbonus(); // No implementation }

Here is a snapshot of the modified program working

Part 6: Shapes Test//Enrique Carbajal //ShapeTest.javapackage Part6;

public class ShapeTest { private Shape shapeArray[];

private TwoDimensionalShape twoDArray[]; private ThreeDimensionalShape threeDArray[];

// create shapes public ShapeTest() { shapeArray = new Shape[4]; twoDArray = new TwoDimensionalShape[2]; threeDArray = new ThreeDimensionalShape[2]; Circle circle = new Circle( 12, 88, 18 ); shapeArray[0] = circle; twoDArray[0] = circle;

Square square = new Square( 60, 96, 95 ); shapeArray[1] = square; twoDArray[1] = square; Sphere sphere = new Sphere( 7, 90, 76 ); shapeArray[2] = sphere; threeDArray[0] = sphere;

Cube cube = new Cube( 69, 58, 72 ); shapeArray[3] = cube; threeDArray[1] = cube; }

// display shape info public void displayShapeInfo() { // call method print on all shapes for ( int i = 0; i < shapeArray.length; i++ ) { //First for loop System.out.print( shapeArray[i].getName() +

": " ); shapeArray[i].print(); } System.out.println(); System.out.println("The area for the 2D shapes are:"); // print area of 2D shapes for ( int j = 0; j < twoDArray.length; j++ ){ System.out.println( twoDArray[ j ].getName() + "'s area is " + twoDArray[ j ].area() );} System.out.println(); System.out.println("The volume and area for the 3D shapes are:"); // print area and volume of 3D shapes for ( int k = 0; k < threeDArray.length; k++ ) { System.out.println( threeDArray[ k ].getName() + "'s area is " + threeDArray[ k ].area() ); System.out.println( threeDArray[ k ].getName() + "'s volume is " + threeDArray[ k ].volume() ); }//For loop on threeDArray }//First for loop //End of Method Display Shape Info

// create ShapeTest object and display info public static void main( String args[] ) { ShapeTest driver = new ShapeTest(); driver.displayShapeInfo(); }

} // end class ShapeTest

//Enrique Carbajal//Shape abstract classpackage Part6;

public abstract class Shape { private int x; // Sets x coordinate of shape private int y; // Sets y coordinate of shape // constructor public Shape( int x0, int y0 ) { x = x0; y = y0; }//End of two argument constructor // set x coordinate public void setX( int x0 ) { x = x0; } // set y coordinate public void setY( int y0 ) { y = y0; } // get x coordinate public int getX() { return x; }

// get y coordinate public int getY() { return y; }

// abstract methods public abstract String getName(); public abstract void print();} // end class Shapepackage Part6;

public abstract class TwoDimensionalShape extends Shape {

private int dimension1;private int dimension2;

// constructor public TwoDimensionalShape( int x, int y, int d1, int d2) { super( x, y ); dimension1 = d1; dimension2 = d2; }

// set methods public void setDimension1( int d ) { dimension1 = d; }

public void setDimension2( int d ) { dimension2 = d; }

// get methods public int getDimension1() { return dimension1; }

public int getDimension2() { return dimension2; }

// abstract methods public abstract double area();} // end class TwoDimensionalShape

package Part6;

public class Square extends TwoDimensionalShape {

public Square( int x , int y, int length ){

super( x, y ,length , length);//Passes values to super class constructor}//End of default constructor

public String getName(){

return "Square";}

public void print(){ System.out.println( "(" + super.getX() + "," + super.getY() +") " + "side: " + super.getDimension1() );

}

public double area(){

return (double) ( super.getDimension1() * super.getDimension1());}

}//End of class definitionpackage Part6;

public class Circle extends TwoDimensionalShape {

final double pi = 3.14;

//Circle Constructorpublic Circle( int x, int y , int radius ){

super( x, y , radius, radius);// Calls Superclass TwoDimensionalShape constructor

}//End of default constructor

public String getName(){

return "Circle";}//COncrete implementation of abstract class

public void print(){ System.out.println( "(" + super.getX() + "," + super.getY() +") " + "side: " + super.getDimension1() );

}

@Overridepublic double area() {

return (double)( pi * super.getDimension1() * super.getDimension1() );

}

}//End of Circle class definition

package Part6;

public abstract class ThreeDimensionalShape extends Shape{private int dimension1;private int dimension2;private int dimension3;

// constructor public ThreeDimensionalShape( int x, int y, int d1, int d2, int d3 ) { super( x, y ); dimension1 = d1; dimension2 = d2; dimension3 = d3; }

// set methods public void setDimension1( int d ) { dimension1 = d; }

public void setDimension2( int d ) { dimension2 = d; } public void setDimension3( int d ) { dimension3 = d; }

// get methods public int getDimension1() { return dimension1; }

public int getDimension2() { return dimension2; } public int getDimension3() { return dimension3; }

// abstract methods public abstract double area(); public abstract double volume();} // end class ThreeDimensionalShape

package Part6;

public class Cube extends ThreeDimensionalShape {

// constructor public Cube( int x, int y, int side ) { super( x, y, side, side, side ); } // overridden methods public String getName() { return "Cube"; }

public double area() { return ( int )( 6 * super.getDimension1() * super.getDimension1() ); }

public double volume() { return ( int ) ( super.getDimension1() * super.getDimension1() * super.getDimension1() ); }

public void print() { System.out.println( "(" + super.getX() + "," + super.getY() +") " + "side: " + super.getDimension1() ); }

// set method public void setSide( int side ) { super.setDimension1( side ); }

// get method public int getSide() { return super.getDimension1(); }} // end class Cube

package Part6;

public class Sphere extends ThreeDimensionalShape {

final double pi = 3.14;

public Sphere( int x , int y, int d1 )//Default constructor{

super( x, y, d1, d1, d1);}//End of default constructor

public String getName(){

return "Sphere";}

public void print() { System.out.println( "(" + super.getX() + "," + super.getY() +") " + "side: " + super.getDimension1() ); } public double area(){

return (double )( 4 * pi * super.getDimension1() * super.getDimension1() );

}

public double volume(){

return (double) ( 1.3 * pi * super.getDimension1() * super.getDimension1() * super.getDimension1() );

}

// set method public void setSide( int side ) { super.setDimension1( side ); }

// get method public int getSide() { return super.getDimension1(); }

}//End of class definition

Here is a screenshot of this program working correctly

I gave myself full points for every assignment because I was able to get every program to work correctly.