1

我只是通过内部类,但我得到了错误的输出。

我基本上是在尝试使用地址类创建一个具有两个不同地址的学生对象,但我得到了一些荒谬的输出。我显然在做一些完全错误的事情,所以如果有人能提供帮助,那就太好了。

学生班级:

public class  Student {
    private String name;
    private Address homeAddress, uniAddress;

    public Student(String name, int houseNumber, String homeStreet, int uniNumber, String      uniStreet) {
        this.name = name;
        homeAddress = new Address(houseNumber, homeStreet);
        uniAddress = new Address(uniNumber, uniStreet);

   }

   public void setUniAddress (Address uniAddress){

       this.uniAddress = uniAddress;

   }

   public class Address {
        public int number;
        private String street;

        public Address(int no, String street) {
            number = no;
            this.street = street;
        }
   }

   public String toString()     {

        String a = name + "\n" + homeAddress + " " + uniAddress;
        return a;
   }
}

和我的测试学生类来创建对象并运行 toString:

 public class  TestStudent {
 public static void main(String[] args) {

    Student s1 = new Student("Cathy", 21, "Smithfield Drive", 72, "Nottingham Drive");
    Student.Address anotherAddress
          = s1.new Address(8, "Deerfield Way");     

    System.out.println(s1.toString());
 }

我得到的输出是:Cathy student.Student$Address@2760e8a2 student.Student$Address@4b48f7e0

谢谢

4

2 回答 2

2

如果你想要漂亮的输出而不是类似的东西Cathy student.Student$Address@2760e8a2,那么你需要重写toString()你的类中的方法Address

目前,toString()您拥有的方法是在课堂Student上,而不是在课堂上Address- 仔细检查{and }

于 2013-11-07T10:55:56.247 回答
2

您还需要实现 Adress 的 toString() 方法。

 public class Address {
    public int number;
    private String street;
    public Address(int no, String street) {
        number = no;
        this.street = street;
    }

public String toString() {
return street + Integer.valueOf(number);
    }
于 2013-11-07T10:56:05.917 回答