好吧,这很简单。
我需要在特定索引处打印出对象的所有参数。但是,所有对象都显示内存地址。我知道你必须覆盖toString方法。但我不确定在哪里。
任何帮助都会很棒!
这是我的员工类代码:
public class Employee {
private String name;
private int age;
private String department;
public String getDept(){
return department;
}//end dept
public void setDept(String dept){
this.department = dept;
}//end
public String getName(){
return name;
}//end name
public void setName(String n){
this.name = n;
}//end
public int getAge(){
return age;
}//end age
public void setAge(int a){
this.age = a;
}//end
public Employee (String n,int age,String dept){
this.name = n;
this.age = age;
this.department = dept;
}//end employee
} //结束课
这是我的主要方法中的代码:
public class Company {
public static void main(String [] args){
Employee[] e = new Employee[13];
e[0] = new Employee("Counting Guru",55,"Accounting");
e[1] = new Employee("Counting Pro",45,"Accounting");
e[2] = new Employee("Counting Savvy",40,"Accounting");
e[3] = new Employee("Counting Novice",25,"Accounting");
e[4] = new Employee("Sales Guru",50,"Marketing");
e[5] = new Employee("Sales Pro",48,"Marketing");
e[6] = new Employee("Sales Savvy",38,"Marketing");
e[7] = new Employee("Hiring Guru",58,"Human Resrouces");
e[8] = new Employee("Hiring Pro",47,"Human Resrouces");
e[9] = new Employee("Hacking Pro",47,"Information Systems");
e[10] = new Employee("Hacking Guru",51,"Information Systems");
e[11] = new Employee("Hacking Savvy",38,"Information Systems");
e[12] = new Employee("Hacking Novice",23,"Information Systems");
for(int i = 0;i<e.length;i++){
System.out.println(e[i]);
}//end
}//end main
}//end company
答案 0 :(得分:5)
将toString()
放在Employee类中,可能上面有@Override标记。
@Override
public String toString() {
return name + ", " + age + ", " + department;
}
答案 1 :(得分:2)
class Employee {
@Override
public String toString() {
return String.format("[Employee name=%s, age=%d, department=%s]",
name, age, department);
}
}
现在只需循环遍历员工数组,然后按原样打印员工对象。