In: Computer Science
Write a class encapsulating the concept of a Student Employee, assuming that a student has the following attributes: last name, first name, id, array of hours worked weekly. Include a constructor, the accessors and mutators, and method toString. Also code the following methods: one returning the average weekly hours and a method to add the hours to the array of hoursWorked (this means creating a large array). Let this array store the weekly hours (not daily hours) worked for each student employee. Write a client class to create 2 student objects and test all your methods.
I've been working for a few days and I'm not sure why I can't figure it out.
Please show using only import.java.util.Scanner/ import java.io.*; Thank you.
Solution:
code:
Student.java:
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
import java.util.Arrays;
public class Student {
private String fName;
private String lName;
private String id;
private int hoursWorked[];
private int index = 0;
public Student(String afName, String alName, String aId,
int[] ahoursWorked) {
super();
fName = afName;
lName = alName;
id = aId;
hoursWorked = ahoursWorked;
}
public String getfName() {
return fName;
}
public void setfName(String afName) {
fName = afName;
}
public String getlName() {
return lName;
}
public void setlName(String alName) {
lName = alName;
}
public String getId() {
return id;
}
public void setId(String aId) {
id = aId;
}
public int[] gethoursWorked() {
return hoursWorked;
}
public void sethoursWorked(int[] ahoursWorked) {
hoursWorked = ahoursWorked;
}
@Override
public String toString() {
return "Student [fName=" + fName + ", lName=" + lName + ", id=" +
id + ", hoursWorked="
+ Arrays.toString(hoursWorked) + "]";
}
public double averageWeeklyHours() {
double sum = 0;
for (double d : hoursWorked) {
sum += d;
}
return sum / hoursWorked.length;
}
public void addHours(int h) {
int temp[] = new int[hoursWorked.length + 1];
for (int i = 0; i < hoursWorked.length; i++)
temp[i] = hoursWorked[i];
temp[temp.length - 1] = h;
hoursWorked = temp;
}
}
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
StudentDriver.java:
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
public class StudentDriver {
public static void main(String[] args) {
int hour1[] = { 12, 15, 21 };
int hour2[] = { 7, 22, 53 };
Student std1 = new Student("Lorel", "Ipsum", "1",
hour1);
Student std2 = new Student("Bob", "Marley", "2", hour2);
System.out.println(std1);
System.out.println(std2);
System.out.println("Average : " + std1.averageWeeklyHours());
System.out.println("Average : " +
std2.averageWeeklyHours());
}
}
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Output:
Hit the thumbs up if you liked the answer. :)
Hit the thumbs up if you liked the answer. :)