Java toString 方法 - 打印不正确

标签 java string return output tostring

我试图从 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/

相关文章:

Java Swing - 在运行时动态切换语言环境

java - 使用JAXB解析java XML

python - 从域名地址中提取名称实体

c++ - 该代码中的错误是什么?

c - Memcpy 一个 str[ ] 到 str*

java - iText PdfTextExtractor getTextFromPage 异常 "Error reading string at file pointer"

java - Spring Security 中奇怪的对象类型更改

java - return 语句应该是代码块中的最后一条指令吗?

ruby-on-rails - 如果评估的最后一个语句是 If 语句,Ruby 会返回什么

php - 在 PHP 中保护来自 "include pollution"的变量