【发布时间】:2014-03-13 19:23:38
【问题描述】:
在我的驱动程序中使用定义的 toString 方法打印出 StaffMember 对象数组时遇到问题。我不断收到找不到符号错误,我很困惑我需要在我的驱动程序中用什么替换 staffList 以使事情顺利进行。
这是我遇到的问题的一部分:“您的程序应首先将所有员工(使用 StaffMember 类的 toString() 方法)打印到终端窗口”
这是我的代码(Staff 和 StaffMember 课程来自教科书,不需要为作业进行更改,所以所有问题都与我的驱动程序有关)。
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 ("-----------------------------------");
}
}
}
这是抽象类:
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();
}
到目前为止,这是我为司机得到的:
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());
}
}
我已经尝试了各种方法来代替 staffList 和 staffList[i],但我似乎无法弄清楚。非常感谢任何可以帮助我的人
【问题讨论】:
-
您的
EmployeeBinaryList#main中的staffList是什么? -
另外,
System.out.println(staffList[i]);比System.out.println(staffList[i].toString());更安全,因为您可能会暴露您的程序以引发 NPE。 -
staffList 是 Staff 类中包含我需要打印的所有员工信息的数组的名称。
-
在你的主方法类中创建一个 Staff 类的对象,即 EmployeeBinaryList,然后从 Staff 对象中获取 Stafflist 数组。
标签: java arrays object tostring