简体   繁体   English

无法将ArrayList作为表打印到控制台

[英]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). 然后将行拆分为各个字段,并进行必要的转换(从String到int或double)。 Then I will use the static factory method to create the SalariedEmployee/HourlyEmployee object and add it to the ArrayList . 然后,我将使用静态工厂方法创建SalariedEmployee/HourlyEmployee对象,并将其添加到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. 所有货币栏都应有2个头寸的仓位。 Then I need to call the totalPay method to calculate the employee's total pay. 然后,我需要调用totalPay方法来计算员工的总工资。 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. 我想使用System.out.printf格式化和显示行。

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: 我的子类别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: 我的子类别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: 您的ArrayList定义为包含字符串:

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

And your factory method returns an Employee: 您的工厂方法将返回一个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. 因此,您不能将Employee类型的对象添加到String的ArrayList中。 If you want to fix this, change your ArrayList to hold objects of type Employee: 如果要解决此问题,请更改ArrayList以容纳Employee类型的对象:

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

Try changing in your main: 尝试更改主目录:

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

to

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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