输出数组信息使用toString方法

时间:2015-12-15 09:07:04

标签: java arrays tostring

当我运行这个程序时,有人可以解释为什么没有打印?

public class Teacher {

public static void main(String [] args) {

   Teacher [] teacher = new Teacher[2];
   teacher[0] = new Teacher ("Jack Campbell", 74);
   teacher[1] = new Teacher ("Mary Smith", 69;
   }
}


public class testTeacher {

   String name;
   int age;

   public testTeacher (String name, int age) {
   }

   public String toString() {
     String teacher = name;
     teacher += getAge();
     teacher += "Age is" + age;
     return teacher;
   }

   public void setName (String nam) {
      name = nam;
   }

   public String getName() {
      return name;
   }

   public void setAge(int Age){
      age = Age;
   }

   public String getAge() {
      return age;
   }
}

我在这里缺少什么?我认为这与toString方法有关,但我并不积极。在我的代码中,它说该方法从未使用过,我不确定为什么。

2 个答案:

答案 0 :(得分:0)

您可以这样写:

class Teacher {

  public static void main(String [] args) {
     Teacher [] teacher = new Teacher[2];
     teacher[0] = new Teacher ("Jack Campbell", 74);
     teacher[1] = new Teacher ("Mary Smith", 69);
     System.out.println(teacher[0].toString());
  }

  String name;
  int age;

  public Teacher (String name, int age) {
     this.name = name;
     this.age = age;
  }

  @Override
  public String toString() {
     String teacher = name;
     teacher += "Age is" + age;
     return teacher;
  }
}

答案 1 :(得分:0)

如果您想打印阵列中的所有教师:

for (int i=0; i < teacher.length; i++) { 
System.out.println(teacher[i].toString();)
}

我建议你做一些关于面向对象编程,数组和循环的基础java教程。还要确保使用像eclipse(免费软件)这样的良好开发环境来获得良好的代码突出显示和有意义的错误消息。