Day 3
June 5th (Wednesday)
Objectives:
Objectives:
Classes I: Instance variables, methods (get and set methods, constructors); data abstraction; public, private access; class variables, methods.
Lab assignment:
Lab assignment:
- Practice Exercises for Day 3
- file: TestFraction.java
- attendance and exercises completion status: https://goo.gl/5qTXjA
Lecture slides:
Lecture slides:
- pdf file: Slides for Day 3
Hourly Employee:
- First version
// HourlyEmployee.java
public class HourlyEmployee
{
String lastName;
String firstName;
Double hourlyRate;
public HourlyEmployee(String last, String first, double rate)
{
this.lastName = last;
this.firstName = first;
this.hourlyRate = rate;
}
public String toString()
{
return (String.format("%s, %s %.2f",
this.lastName, this.firstName, this.hourlyRate));
}
}
- Final version:
// -------------------------- File HourlyEmployee.java ---------------------
// HourlyEmployee.java
public class HourlyEmployee
{
static int numberOfEmployees;
private String lastName;
private String firstName;
private Double hourlyRate;
private int employeeID;
public HourlyEmployee(String last, String first, double rate)
{
lastName = last;
firstName = first;
hourlyRate = rate;
employeeID = numberOfEmployees++;
}
public String toString()
{
return (String.format("%05d %s, %s $%.2f per hour", employeeID, lastName, firstName, hourlyRate));
}
}
// -------------------------- File HourlyEmployeeTest.java ---------------------
import java.util.Scanner;
public class HourlyEmployeeTest
{
static final int NUMBER_OFFICES = 20;
static HourlyEmployee hourlyEmployees[] = new HourlyEmployee[NUMBER_OFFICES];
static Scanner input = new Scanner(System.in);
static boolean hiring = true;
public static void main(String[] args)
{
for (int i = 0; i < NUMBER_OFFICES; i++)
if (!hire(i))
break;
for (int i = 0; i < HourlyEmployee.numberOfEmployees; i++)
System.out.println(hourlyEmployees[i].toString());
}
public static boolean hire(int i)
{
System.out.print("Enter Employee's First Name: ");
String first = input.next();
if (first.equals("Q"))
return false;
System.out.print("Enter Employee's Last Name: ");
String last = input.next();
System.out.print("Enter Employee's Hourly Rate: ");
double rate = input.nextDouble();
hourlyEmployees[i] = new HourlyEmployee(last, first, rate);
return true;
}
}