gpt4 book ai didi

Java toString 方法 - 打印不正确

转载 作者:行者123 更新时间:2023-12-01 17:13:03 25 4
gpt4 key购买 nike

我试图从 Employee 类获取 toString,但它所做的只是给我一个输出 [ ]。我得到了 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

最佳答案

您正在调用 ArrayListtoString 方法,而不是任何 Employee 的方法。事实上,您还没有创建该类的实例。尝试:

System.out.println(new Employee());

关于Java toString 方法 - 打印不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23149597/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com