简体   繁体   中英

Trouble printing out ArrayList as Table to the Console

I am trying to read in each line of the file which should be in the following format:-

 name    type   hours   wage   salary

And then split the line up into individual fields and do any necessary conversions (from String to int or double). Then I will use the static factory method to create the SalariedEmployee/HourlyEmployee object and add it to the ArrayList .

I want to loop the employees list and print out a table to the console that lists each employee's name, type, hours and total pay. Each column needs be aligned, Strings – left aligned, numbers – right aligned. All money columns should have 2 positions for cents. Then I need to call the totalPay method to calculate the employee's total pay. I also want to keep a grand total of the total pay for all employees and display it on a separate line at the bottom. Make sure the columns align with their headers. I want to use System.out.printf to format and display the rows.

The issue is I've repeatedly tried to print out the employees list but run into errors

private static final String fileName = "input.txt";

public static void main(String[] args) {

    List<Employee> employees = new ArrayList<>(); //
    String line = null;
    BufferedReader reader = null;

    try{
        reader = new BufferedReader(new FileReader(new File(fileName)));

        while((line = reader.readLine()) != null){
            String[] information = line.split("\\s+");
            String name = information[0];
            String type = information[1];
            int hours;
            hours = Integer.parseInt(information[2]);
            double wage = Double.parseDouble(information[3]);
            double salary = Double.parseDouble(information[4]);

            employees.add(Employee.factory(name, type, hours, wage, salary));

            }
        reader.close();

    } catch (IOException ex) {
        System.out.println("Command-line argument is missing");
        System.exit(1);
    }

    int size = employees.size();

    System.out.println("Name  Type    Hours   Total Pay");
    for(int i =0; i < size; i++){
         System.out.println(employees.getName() + "    " +  
         employees.getType() + "  " + employees.getHoursWorked() + " " 
         Employee.totalPay());
    }
}

My superclass Employee:

public abstract class Employee{
   protected String name;
   protected int hours;

   public String getName(){
      return name;
   }
   public int getHours(){
      return hours;
   }
   public abstract String getType();

   public Employee(String name, int hours){
       this.name = name;
       this.hours = hours;
   }

   public abstract double totalPay();

   public static Employee factory(String name, String type, int hours, double 
       wage, double salary){
       if(type.equals("Salaried") || type.equals("SALARIED") || 
           type.equals("salaried")){
           Employee object = new SalariedEmployee(name, hours, (int)salary);
               return object;
       }else if(type.equals("Hourly") || type.equals("HOURLY") || 
            type.equals("hourly")){
            Employee object = new HourlyEmployee(name, hours, (int)wage);
                return object;
       }else{
           return null;
       }

   }

My subclass HourlyEmployee:

public class HourlyEmployee extends Employee {

    private double wage; // wage per hour
    private double hoursWorked; // hours worked for week
    private int workedHours = (int)hoursWorked;
    public HourlyEmployee(String name, double hourlyWage, int workedHours){

    super(name, workedHours);
    setWage(hourlyWage); // validate hourly wage
    setHours(workedHours); // validate hours worked
    } 

    public void setWage(double hourlyWage)
    {
       if ( hourlyWage >= 0.0 )
           wage = hourlyWage;
       else
           throw new IllegalArgumentException("Hourly wage must be >= 0.0" );
    } 

    public double getWage()
    {
       return wage;
    } 

    public void setHours(double hoursWorked)
    {
       if ( ( hoursWorked >= 0.0 ) && ( hoursWorked <= 168.0 ) )
           this.hoursWorked = hoursWorked;
       else
           throw new IllegalArgumentException("Hours worked must be >= 0.0 and 
           <= 168.0" );
       } 

    public double getHoursWorked()
    {
         return hoursWorked;
    } 
    @Override                                                             
    public String getType(){ 
         return "Hourly";
    }       
    @Override                                                             
    public double totalPay(){
        return getWage() * getHours(); 
    }
}

My subclass SalariedEmployee:

public class SalariedEmployee extends Employee {
    private double salary; // wage per year
    private double hoursWorked; // hours worked for week
    private int workedHours = (int)hoursWorked;
    public SalariedEmployee(String name, double salary, int workedHours){
    super(name, workedHours);
    setSalary(salary); // validate hourly wage
    setHours(workedHours); // validate hours worked
    } 

    public void setSalary(double employeeSalary)
    {
        if ( salary >= 0.0 )
            salary = employeeSalary;
        else
            throw new IllegalArgumentException("Salary must be >= 0.0" );
    } 

    public double getSalary()
    {
        return salary;
    } 

    public void setHours(double hoursWorked)
    {
        this.hoursWorked = hoursWorked;

    } 

    public double getHoursWorked()
    {
        return hoursWorked;
    } 

    @Override
    public String getType() {
       return "Salaried";
    }

    @Override
    public double totalPay() {
       return (getSalary())/52;  
    }

}

Your ArrayList is defined to hold Strings:

List<String> employees = new ArrayList<>();

And your factory method returns an Employee:

public static Employee factory(String name, String type, int hours, double 
   wage, double salary)

Therefore you can't add an object of type Employee, to the ArrayList of Strings. If you want to fix this, change your ArrayList to hold objects of type Employee:

List<Employee> employees = new ArrayList<>();

Try changing in your main:

List<String> employees = new ArrayList<>();

to

List<Employee> employees = new ArrayList<>();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM