Printing an Array of Staff objects with a toString - java

I'm having trouble printing out an array of StaffMember objects by utilizing the defined toString method with my driver. I keep getting a cannot find symbol error and I'm confused as to what I need to replace the staffList with in my driver to make things work out.
This is the part of the question I'm stuck on "Your program should first print all the staff members (use toString() method of the StaffMember class) to the terminal window"
Here is my code (the Staff and StaffMember classes are from the textbook and were not required to be changed for the assignment, so all problems are with my driver).
public class Staff
{
private StaffMember[] staffList;
public Staff ()
{
staffList = new StaffMember[6];
staffList[0] = new Executive ("Sam", "123 Main Line",
"555-0469", "123-45-6789", 2423.07);
staffList[1] = new Employee ("Carla", "456 Off Line", "555-0101",
"987-65-4321", 1246.15);
staffList[2] = new Employee ("Woody", "789 Off Rocker", "555-0000",
"010-20-3040", 1169.23);
staffList[3] = new Hourly ("Diane", "678 Fifth Ave.",
"555-0690", "958-47-3625", 10.55);
staffList[4] = new Volunteer ("Norm", "987 Suds Blvd.",
"555-8374");
staffList[5] = new Volunteer ("Cliff", "321 Duds Lane",
"555-7282");
((Executive)staffList[0]).awardBonus (500.00);
((Hourly)staffList[3]).addHours (40);
}
public void payday ()
{
double amount;
for (int count=0; count < staffList.length; count++)
{
System.out.println (staffList[count]);
amount = staffList[count].pay();
if (amount == 0.0)
System.out.println ("Thanks!");
else
System.out.println ("Paid: " + amount);
System.out.println ("-----------------------------------");
}
}
}
This is the abstract class:
abstract public class StaffMember
{
protected String name;
protected String address;
protected String phone;
//-----------------------------------------------------------------
// Constructor: Sets up this staff member using the specified
// information.
//-----------------------------------------------------------------
public StaffMember (String eName, String eAddress, String ePhone)
{
name = eName;
address = eAddress;
phone = ePhone;
}
//-----------------------------------------------------------------
// Returns a string including the basic employee information.
//-----------------------------------------------------------------
public String toString()
{
String result = "Name: " + name + "\n";
result += "Address: " + address + "\n";
result += "Phone: " + phone;
return result;
}
//-----------------------------------------------------------------
// Derived classes must define the pay method for each type of
// employee.
//-----------------------------------------------------------------
public abstract double pay();
}
And this is what I've gotten for a driver so far:
import java.util.*;
public class EmployeeBinaryList
{
public static void main (String args[])
{
for (int i = 0; i < staffList.length; i++)
System.out.println(staffList[i].toString());
}
}
I've tried various things in place of the staffList and staffList[i], but I just can't seem to figure it out. Thanks a ton to anyone who can help me

you need to think about scope here. A variables scope is where that variable can be accessed. The easiest way to know the scope of a variable is by the curly braces. a variable is only accessible directly within the braces where it was defined. So, staffList is defined in the staff class, as such it is only accessible directly in the staff class.
you would have to access that variable through an object of the staff class:
System.out.println(StaffObject.StaffList) //StaffObject would be an object of the Staff class
however, in this case you also need to look at whether the variable is public or private. Private means it can not be accessed directly outside of its class. so in this case StaffObject.staffList would not be accessible outside of the Staff class
In order to access that StaffList variable you need what's called an Accessor method. A method which is public, and allows access to the variable for printing purposes.
so, here's whatcha gotta do:
First off you need an object of the staff class
Then, you need to use that object to access the appropriate Accessor method for printing
take a good look at the code, chances are its all there for a reason.
good luck!!

package com.cisco.staff;
public class Staff
{
private StaffMember[] staffList;
public Staff ()
{
staffList = new StaffMember[6];
staffList[0] = new Executive ("Sam", "123 Main Line",
"555-0469", "123-45-6789", 2423.07);
staffList[1] = new Employee ("Carla", "456 Off Line", "555-0101",
"987-65-4321", 1246.15);
staffList[2] = new Employee ("Woody", "789 Off Rocker", "555-0000",
"010-20-3040", 1169.23);
staffList[3] = new Hourly ("Diane", "678 Fifth Ave.",
"555-0690", "958-47-3625", 10.55);
staffList[4] = new Volunteer ("Norm", "987 Suds Blvd.",
"555-8374");
staffList[5] = new Volunteer ("Cliff", "321 Duds Lane",
"555-7282");
/* ((Executive)staffList[0]).awardBonus (500.00);
((Hourly)staffList[3]).addHours (40);*/
}
public void payday ()
{
double amount;
for (int count=0; count < staffList.length; count++)
{
System.out.println (staffList[count]);
amount = staffList[count].pay();
if (amount == 0.0)
System.out.println ("Thanks!");
else
System.out.println ("Paid: " + amount);
System.out.println ("-----------------------------------");
}
}
public StaffMember[] getStaffList() {
return staffList;
}
public void setStaffList(StaffMember[] staffList) {
this.staffList = staffList;
}
}
package com.cisco.staff;
abstract public class StaffMember
{
protected String name;
protected String address;
protected String phone;
//-----------------------------------------------------------------
// Constructor: Sets up this staff member using the specified
// information.
//-----------------------------------------------------------------
public StaffMember (String eName, String eAddress, String ePhone)
{
name = eName;
address = eAddress;
phone = ePhone;
}
//-----------------------------------------------------------------
// Returns a string including the basic employee information.
//-----------------------------------------------------------------
public String toString()
{
String result = "Name: " + name + "\n";
result += "Address: " + address + "\n";
result += "Phone: " + phone;
return result;
}
//-----------------------------------------------------------------
// Derived classes must define the pay method for each type of
// employee.
//-----------------------------------------------------------------
public abstract double pay();
}
package com.cisco.staff;
import java.util.List;
public class EmployeeBinaryList
{
public static void main (String args[])
{
Staff staff = new Staff();
StaffMember[] staffList = staff.getStaffList();
for (int i = 0; i < staffList.length; i++)
System.out.println(staffList[i].toString());
}
}
package com.cisco.staff;
public class Executive extends StaffMember {
protected String somestrString;
protected double somelong;
public Executive(String eName, String eAddress, String ePhone, String someString , double pay) {
super(eName, eAddress, ePhone);
this.somestrString= someString;
this.somelong=pay;
// TODO Auto-generated constructor stub
}
#Override
public double pay() {
// TODO Auto-generated method stub
return 0;
}
}
package com.cisco.staff;
public class Volunteer extends StaffMember {
protected String somestrString;
protected double somelong;
public Volunteer(String name, String address, String phone) {
super(name, address, phone);
// TODO Auto-generated constructor stub
}
#Override
public double pay() {
// TODO Auto-generated method stub
return 0;
}
}
package com.cisco.staff;
public class Employee extends StaffMember {
protected String somestrString;
protected double somelong;
public Employee(String name, String address, String phone,
String somestrString, double somelong) {
super(name, address, phone);
this.somestrString=somestrString;
this.somelong=somelong;
}
#Override
public double pay() {
// TODO Auto-generated method stub
return 0;
}
}
package com.cisco.staff;
public class Hourly extends StaffMember {
protected String somestrString;
protected double hourly;
public Hourly(String eName, String eAddress, String ePhone, String somString, double hourly) {
super(eName, eAddress, ePhone);
this.somestrString=somString;
this.hourly=hourly;
// TODO Auto-generated constructor stub
}
#Override
public double pay() {
// TODO Auto-generated method stub
return 0;
}
}

Related

why i am getting an error when i try to over ride a method

Hello and good morning guys I'm new to Java, I've encountered some problems while doing my home work. It is related to inheritance.
I need to create a super class named Employee where the variable name and Employee number are kept. And then I need to create a displayInfo() methods to print all the variables.
Then I've been assigned to create a subclass where i calculate the salary and make an overridden method to print the variables from the super class and add the salary to it using the displayInfo() method. But when I try to use it in the subclass, there is an error shown up where it says:
the field employee.number is not visible
Is there any way I can solve this?
Thank you very much for your help! Here is the code I've tried so far
public class Employee {
private String name;
private String number;
private String date;
public Employee()
{
}
public Employee(String name,String number,String date)
{
this.name=name;
this.number=number;
this.date=date;
}
public String getName()
{
return name;
}
public String getNumber()
{
return number;
}
public String getDate()
{
return date;
}
public void displayInfo()
{
System.out.println("Name = "+ name + "Number = "+number+ " Date = " + date);
}
}
\\ my sub class
public class ProductionWorker extends Employee {
private int shift;// 1 = day, 2 = night
private double HoursOfWorking;// day = RM10, night = RM12.50
public ProductionWorker(int shift,int HoursOfWorking)
{
this.shift=shift;
this.HoursOfWorking=HoursOfWorking;
}
public int getShift()
{
return shift;
}
public double getHoursOfWorking()
{
return HoursOfWorking;
}
public double calculateSalary()
{
if(shift==1)
{
return HoursOfWorking * 10 * 20;
}
else
{
return HoursOfWorking * 12.5 * 20;
}
}
public void displayInfo() // this is where the error is encountered
{
System.out.println("Name = "+ name + "Number = "+number+ " Date = " + date + "Sallary = "+ calculateSalary());
}
}
As the below fields are private
private String name;
private String number;
private String date;
you do not have access to them in the subclass, so either make them protected or use the getter methods.
EDIT: I actually take back my answer below. That will only work if the classes are in the same file like this:
class OuterClass
{
public class Employee
{
// ...
}
public class ProductionWorker extends Employee
{
// ...
}
}
You can either change the variables visibility to public/protected or use the getter methods you defined in your Employee class. I'd recommend using the getter methods.
In order to access the values of the Employee class in your subclass ProductionWorker, you have to use the super keyword.
public void displayInfo()
{
System.out.println("Name = " + super.name + "Number = " + super.number + " Date = " + super.date + "Salary = " + calculateSalary());
}
since number is declared as private it is not visible you have to use
your getNumber() method

Hiring a person by surname

Could anyone help me fix the below-attached code? I've written a Java method that hires a person by surname, and what I mean by that is that the value passed in the method should be the last name of an object reference (an object of a class Employee which we desire to hire in the company).
However, the program is complaining that the surname cannot be resolved to a type. Now, getSurname() is a method of a private instance variable defined in Employee which is an abstract class (and a superclass for two subclasses Worker and Officer, but that's irrelevant to the problem). Anyone willing to give me a hand?
public class CompanyArrayList {
private ArrayList<Employee> arrayList;
public CompanyArrayList(int employeeNumber) {
ArrayList<Employee> arrayList = new ArrayList<Employee>(employeeNumber);
}
public String hire(Employee employee.getSurname()) { // the object of this class will be generated in the "main" method.
for (int i = 0; i < employeeNumber; i++) {
if (!arrayList.contains(employee.getSurname())) {
arrayList.add(employee);
return "Hired"; // "return" terminates the execution of the method.
}
} // WHY?
}
public String fire(Employee employee) {
for (Employee i : arrayList) {
if (employee.getSurname().equals(i.getSurname())) {
arrayList.remove(employee);
return "Fired"; // returns nothing and terminates the method execution.
}
}
return "The person of the" + employee.getSurname() + " surname doesn't work in the company";
}
}
public abstract class Employee {
private String surname;
private float contract; // contract = workperiod
public String getSurname() { // Here we're asking about a surname of an employee
return surname;
}
public float getContract() {
return contract;
}
public Employee(String surname, float contract) {
this.surname = surname;
this.contract = contract;
}
public abstract float pay();
public abstract String group();
}
Change String hire(Employee employee.getSurname()) to String hire(Employee employee).
Edit:
About the Employee that you want to hire() by surname (which I've explained you why this is a bad idea) do this:
public String hire(Employee employee) {
for (int i = 0; i < arrayList.size(); i++) { // you had employeeNumber instead of arraylist.size() but hire() method does not know anything about that variable
Employee temp = arraylist.get(i);
if (temp.getSurname().equals(employee.getSurname)) {
arrayList.add(employee);
return "Hired"; // "return" terminates the execution of the method.
}
}
}

How to stop printing half of my print method

I just need some assistance in stopping the print method. its printing my output twice as car1.print(); car2.print(); is in the print method at the bottom. how do i exclude this without deleting it. It has to be put in the super.print() part.
class Vehicle { // base class
int capacity;
String make;
Vehicle(int theCapacity, String theMake) {
capacity = theCapacity;
make = theMake;
}
void print() {
System.out.println("Vehicle Info:");
System.out.println(" capacity = " + capacity + "cc" );
System.out.println(" make = " + make );
}
}
class Car extends Vehicle {
public String type;
public String model;
public Car(int theCapacity, String theMake, String theType, String theModel) {
super(theCapacity, theMake);
type = theType;
model = theModel;
super.print();
{
System.out.println(" type = " + theType);
System.out.println(" Model = " + theModel);
}
}
}
class Task1 {
public static void main(String[] args) {
Car car1 = new Car(1200,"Holden","sedan","Barina");
Car car2 = new Car(1500,"Mazda","sedan","323");
car1.print();
car2.print();
}
}
You can use the super keyword in the constructor to invoke the super class' constructor and pass parameters to it.
Note that it must be the first statement in the constructor:
class Car extends Vehicle {
public String type;
public String model;
public Car(int theCapacity, String theMake, String theType, String theModel) {
super(theCapacity, theMake); // Here
type = theType;
model = theModel;
}
}
You are missing the Constructor
public Car (int theCapacity, String theMake, String theType, String theModel) {
capacity = theCapacity;
make = theMake;
Type = theType;
Model = theModel;
}
or
public Car (int theCapacity, String theMake, String theType, String theModel) {
super (theCapacity, theMake);
Type = theType;
Model = theModel;
}
You have to call super constructor by passing simply parameters in child class.
public Car(int capacity, String make, String type, String model) {
super(capacity, make); // simply call super
this.type = type;
this.model = model;
}
One of the solution is calling your base class Constructor from child class using super keyword and adding other parameters from child class constructor as mentioned by #Mureinik
Depending on the requirements of the Base Class you can also try using abstract methods. Example code is below.
abstract class Vehicle {
static int capacity;
static String make;
Vehicle(int theCapacity, String theMake) {
capacity = theCapacity;
make = theMake;
}
protected static void print() {
System.out.println("Vehicle Info:");
System.out.println(" capacity = " + capacity + "cc" );
System.out.println(" make = " + make );
// you can use these methods where you want in this base class.
System.out.println(" type = " + getType());
System.out.println(" model = " + getModel());
}
protected abstract String getType();
protected abstract String getModel();
}
public class Car extends Vehicle{
Car(int theCapacity, String theMake) {
super(theCapacity, theMake);
}
/**
* #param args
*/
public static void main(){
print();
}
#Override
protected String getType() {
// TODO Auto-generated method stub
return "Audi";
}
#Override
protected String getModel() {
// TODO Auto-generated method stub
return "Q7";
}
}

Simplify java program using inheritance

I'm currently learning inheritance in java. I have a superclass called Students with subclasses UndergradStudents & GraduateStudents. Both of them have a method called deansHonourList. In the undergrad deansHonourList method it checks if the GPA is greater than 3.5 to qualify for the deans list and for the graduate subclass the gpa has to be greater than 3.75, I have to remove the methods in the subclasses and create one method in the superclass that determines if the student qualifies for the deans honour list. Here is my code so far.
import java.io.*;
public class Activity6C {
public static void main(String[] args) {
Student[] students = new Student[4];
students[0] = new UndergradStudent(8032, "Casper", 2.78, 2);
students[1] = new GraduateStudent(3044, "Sheena", 3.92, "Natural Language Processing");
students[2] = new UndergradStudent(6170, "Yolanda", 4.26, 3);
students[3] = new GraduateStudent(1755, "Geordi", 3.58, "Human-Computer Interaction");
printStudents(students);
printDeansList(students);
System.out.println("\nEnd of processing.");
}
public static void printStudents(Student[] students) {
System.out.println("\nList of all students:\n");
for (int i = 0; i < students.length; i++) {
System.out.println(i + 1 + ": " + students[i]);
}
}
public static void printDeansList(Student[] students) {
System.out.println("\nDean's honour list:\n");
for (int i = 0; i < students.length; i++) {
if (students[i].deansHonourList()) {
System.out.println(students[i]);
}
}
}
}
class Student {
private int number;
private String name;
private double gpa;
public Student(int number, String name, double gpa) {
this.number = number;
this.name = name;
this.gpa = gpa;
}
public double getGPA() {
return gpa;
}
public boolean deansHonourList() {
//Here is where i make my code to determine honour list students
return false;
}
public String toString() {
return number + " " + name + " (" + gpa + ")";
}
}
class UndergradStudent extends Student {
private int year;
public UndergradStudent(int number, String name, double gpa, int year) {
super(number, name, gpa);
this.year = year;
}
public boolean deansHonourList() {
boolean result = false;
if (getGPA() >= 3.5)
result = true;
return result;
}
public String toString() {
return "Undergraduate: " + super.toString() + " year: " + year;
}
}
class GraduateStudent extends Student {
private String thesis;
public GraduateStudent(int number, String name, double gpa, String thesis) {
super(number, name, gpa);
this.thesis = thesis;
}
public boolean deansHonourList() {
boolean result = false;
if (getGPA() >= 3.75)
result = true;
return result;
}
public String toString() {
return "Graduate: " + super.toString() + " thesis: " + thesis;
}
}
Note: This is an exercise and it's not worth much but I would like a hint in the right direction. Here is what the question also specifies.
I have to make it work without using instanceof or getClass(), and without adding any more if-else statements or instance variables. There should be no deansHonourList() method in either GraduateStudent or UndergraduateStudent, and the getGPA() method can be removed.
The hint i got was to add another instance method to the superclass and override it in the subclasses as necessary; call that method in your deansHonourList() method.
I can't think of a way to do this. I mean what can I put in the new instance method that I would make, and then override it in the subclasses.
Thank you for reading my question or any hints you are able to give me.
You'll need a (possibly abstract) method which returns the minimum GPA score acceptable to be considered for the honours list, maybe something like
abstract class Student {
private int number;
private String name;
private double gpa;
public Student(int number, String name, double gpa) {
this.number = number;
this.name = name;
this.gpa = gpa;
}
public double getGPA() {
return gpa;
}
public abstract double getMinimumHonourListGPA();
public boolean deansHonourList() {
boolean result = false;
if (getGPA() >= getMinimumHonourListGPA()) {
result = true;
}
return result;
}
public String toString() {
return number + " " + name + " (" + gpa + ")";
}
}
Then you could implement doing something like...
class UndergradStudent extends Student {
private int year;
public UndergradStudent(int number, String name, double gpa, int year) {
super(number, name, gpa);
this.year = year;
}
public String toString() {
return "Undergraduate: " + super.toString() + " year: " + year;
}
#Override
public double getMinimumHonourListGPA() {
return 3.5;
}
}
Now, if that's not acceptable, you will need to pass the minimum GPA score via the constructor to the parent class, something like...
class Student {
private int number;
private String name;
private double gpa;
private double minimumHonourListGPA;
public Student(int number, String name, double gpa, double minimumHonourListGPA) {
this.number = number;
this.name = name;
this.gpa = gpa;
this.minimumHonourListGPA;
}
public double getGPA() {
return gpa;
}
public boolean deansHonourList() {
boolean result = false;
if (getGPA() >= minimumHonourListGPA) {
result = true;
}
return result;
}
public String toString() {
return number + " " + name + " (" + gpa + ")";
}
}
class UndergradStudent extends Student {
private int year;
public UndergradStudent(int number, String name, double gpa, int year) {
super(number, name, gpa, 3.5);
this.year = year;
}
public String toString() {
return "Undergraduate: " + super.toString() + " year: " + year;
}
}
for example
Ok, what if you had a method 'requiredGPA()', which returned the GPA required to get on the Deans Honour List?
You would then override this method in the subclasses to return their different requirements, and the superclass's deansHonourList() would use the value returned from this method to decide if the student was on the list?
I could give a code example if needed... let me know if I haven't been clear in this answer?
Edit- looks like MadProgrammer has hit the idea I was going for here.
This is an example of Facade design pattern.
Check here.
This pattern is about providing a simple interface to hide the underlying complexity. Interface is used for the invocation of a single and during the run time JVM will determine which method to call. This method is determined by the implementing class of the object on which method was invoked.
In your case Student is going to work as the interface. As others suggested you can use an abstract class with abstract method deansHonourList or you can use an empty implementation.
Now suppose we have empty constructors in all three classes.
Student student1 = new Student();
Student student2 = new UnderGraduateStudent();
Student student3 = new GraduateStudent();
Since a parent class reference variable can hold instance of the child class we are able to assign objects of UnderGraduateStudent and GraduateStudent to the Student type reference variables.
All these three classes have method deansHonourList.
When we call this method on all the three objects as following
student1.deansHonourList(arguments...)
student2.deansHonourList(arguments...)
student3.deansHonourList(arguments...)
JVM will find the correct class from which it has to invoke the method by checking the type of the student1, student2, student3 instances.
Only one of these methods will be called (unlike constructor where super class constructor is called in subclass constructor).
Even if the deansHonourList is called on parent class reference, the method from the child class is called as the reference holds child class instance.
This is called Method Overriding.
Check this out.
Overriding only works in case of non static methods, in case of static methods, parent class methods are called. Since static members are part of the class not the class instance, instance plays no role in the method resolution.
This is called Method Hiding

Getting a StackOverflowError from a Collection Class and its stored objects. Has anyone had a similar dilemma?

I'm completing a Command Design Pattern assignment, and I've run into a StackOverflowError. I've looked up the < init > that comes with the error and it says it has to do with my constructor.
My professor and I have looked it over and we can't seem to find a problem. Maybe an extra set of eyes might do the trick.
Compiled Program:
Exception in thread "main" java.lang.StackOverflowError
at Command.AyyTacoMenu.addItem(AyyTacoMenu.java:39)
at Command.AyyTacoMenu.<init>(AyyTacoMenu.java:13)
at Command.AyyTacoItem.<init>(AyyTacoItem.java:8)
at Command.AyyTacoMenu.addItem(AyyTacoMenu.java:39)
at Command.AyyTacoMenu.<init>(AyyTacoMenu.java:13)
at Command.AyyTacoItem.<init>(AyyTacoItem.java:8)
at Command.AyyTacoMenu.addItem(AyyTacoMenu.java:39)...
Collection Class Code:
package Command;
import java.util.ArrayList;
import java.util.*;
public class AyyTacoMenu {
private ArrayList<AyyTacoItem> atmenu;
public AyyTacoMenu() {
atmenu = new ArrayList<AyyTacoItem>();
// System.out.println("Menu has been set to ArrayList of type AyyTacoItem");
addItem("235", "Breakfast Enchillada", 10.00);
addItem("236", "Burrito Bowl", 8.00);
System.out.println("Items added");
}
public int size() {
// TODO Auto-generated method stub
return atmenu.size();
}
public void addItem(String i, String n, double p) {
AyyTacoItem x = new AyyTacoItem(i, n, p);
atmenu.add(x);
}
public AyyTacoItem get(int i) {
// TODO Auto-generated method stub
return atmenu.get(i);
}
}
Item Class Code:
package Command;
public class AyyTacoItem extends AyyTacoMenu {
private String iD;
private String name;
private double price;
protected AyyTacoItem(String i, String n, double p){
System.out.println("Item being Added");
iD = i;
name = n;
price = p;
System.out.println("Item Added");
}
protected String getID() {
return this.iD;
}
protected String getName() {
return this.name;
}
protected double getPrice() {
return this.price;
}
public String toString() {
String x;
x = ((this.iD) + " | " + (this.name) + " | $" + (this.price));
return x;
}
}
Thank you in advance for your help!
public class AyyTacoItem extends AyyTacoMenu
AyyTacoItem should not extends AyyTacoMenu. Otherwise the base class AyyTacoMenu must be constructed when constructing derived class AyyTacoItem, and AyyTacoMenu's constructor attempted to construct another AyyTacoItem, which leads to infinite recursion.

Categories