我试图从Employee类中获取toString,但它所做的只是给出了[]的输出。我得到了toString方法的输入,但是有关如何让它执行到输出的想法?Java toString方法 - 未正确打印
public class A5
{ // begin class
public static void main(String[] args)
{ // begin main
// ********** CREATE OBJECTS **********
ArrayList<Employee> employeeInfo = new ArrayList<Employee>();
// ********** GET INPUT **********
// get the employee's ID
System.out.println("\nEnter your employee ID.");
ID = keyboard.nextInt(); //get the input and set it to the local varaible ID
//System.out.println("Employee ID: " + ID);
// get the employee's hours worked
System.out.println("\nEnter the amount of hours you worked this week.");
Hours = keyboard.nextInt(); //get the input and set it to the local varaible HoursWorked
//System.out.println("Hours worked: " + Hours);
// get the employee's wage
System.out.println("\nEnter your wage.");
Wage = keyboard.nextDouble(); //get the input and set it to the local varaible Wage
//System.out.println("Employee wage: " + Wage);
// ********** OUTPUT **********
System.out.println(employeeInfo.toString());
// ********** CLOSING MESSAGE **********
System.out.println("\nEnd of Processing!");
} // end main
} // end class
而其他类:
public class Employee
{ // begin class
private int ID; // employee's id
private int Hours; // number of hours worked
private double Wage; // pay per hour
public Employee(int IDnumber)
{
ID = IDnumber;
}
public int getID()
{
return ID;
}
public void setWage(double HourlyWage)
{
Wage = HourlyWage;
}
public double getWage()
{
return Wage;
}
public void setHours(int hoursWorked)
{
Hours = hoursWorked;
}
public double getHours()
{
return Hours;
}
public String toString() // overrides the toString method inherited from object
{ // begin toString
String strout = "\nId \t\t Hours \t\t Rate \t\t Regular Pay \t Overtime Pay \t Gross Pay\n";
strout += ID + "\t " + Hours + "\t\t\t $" + (df1.format(Wage)));
return strout;
} // end toString
} // end class
你正在做的是调用'ArrayList'对象的'toString'方法。你需要调用'Employee'对象的'toString'方法。 –
看起来你的'employeeInfo'对象是空的,你能验证它吗? – amit