我很困惑为什么我的程序按特定顺序打印语句?
我有一个Student class
,里面是Inner Class of Address
。该程序的想法是首先将一个归属地址分配给学生对象,然后通过利用内部地址类分配一个大学/学期时间地址。
代码如下:
学生班(具有内部地址类)
public class Student {
private String name;
private Address homeAddress, uniAddress;
public Student(String name, int houseNumber, String homeStreet) {
this.name = name;
homeAddress = new Address(houseNumber, homeStreet);
}
public String getName() {
return name;
}
public Address getHomeAddress() {
String s = "n/a";
if (homeAddress != null) {
return homeAddress;
} else {
// System.out.println(s);
return null;
}
}
public void setUniAddress(int num, String add) {
uniAddress = new Address(num, add);
}
public Address getUniAddress() {
String s = "n/aa";
//If uniAddress isn't set,
// then "n/aa" gets printed before anything else i/e toString() method - WHY?
if (uniAddress == null) {
System.out.println(s);
return null;
} else {
return uniAddress;
}
}
@Override
public String toString() {
return "NAME: " + getName() + "\n"
+ "HOME ADDRESS: " + getHomeAddress() + "\n"
+ "TERM TIME ADDRESS: " + getUniAddress();
}
// Inner Class
public class Address {
private int number;
private String street;
public Address(int no, String street) {
number = no;
this.street = street;
}
@Override
public String toString() {
//return name + "\n" + number + " " + street;
return number + " " + street;
}
}
} // more Student methods .. }
TestStudent类(使用main方法)
public class TestStudent {
public static void main(String[] args) {
//Home Address
Student s1 = new Student("Cathy", 21, "Smithfield Drive");
//Uni Address
s1.setUniAddress(72, "Nottingham Drive");
Student.Address anotherAddress = s1.new Address(8, "Deerfield Way");
// note the use of new
System.out.println(s1.toString());
}
}
输出结果为:
n/aa
NAME: Cathy
HOME ADDRESS: 21 Smithfield Drive
TERM TIME ADDRESS: null
(all on new lines)
如果我没有为学生分配一个Uni地址(即如果我在主方法中注释掉相应的行 - 调用setUniAddress()
方法),那么我很好奇,为什么'n /来自getUniAddress()方法的aa'是在toString()
方法之前打印的吗? (如上所述)
如果我调用setUniAddress()方法,则输出为:
NAME: Cathy
HOME ADDRESS: 21 Smithfield Drive
TERM TIME ADDRESS: 72 Nottingham Drive
(all on new lines)
这似乎按预期工作。
我也想知道如何,而不是打印'null'到 TERM TIME ADDRESS :(当没有调用setUniAddress()
方法时),我可以返回'n / aa'在它的位置 - 这就是我试图做的事情?
感谢。
答案 0 :(得分:0)
getUniAddress()
调用toString()
,这就是首先打印n/aa
的原因。如果要将“n / aa”打印为默认值 - 将其设置为默认值,例如,将声明更改为:
private Address homeAddress, uniAddress = "n/aa";
@Override
public String toString() {
return "NAME: " + getName() + "\n"
+ "HOME ADDRESS: " + getHomeAddress() + "\n"
+ "TERM TIME ADDRESS: " + getUniAddress(); // <-- here you call getUniAddress() which
// is why "n/aa" is printed first
}
在getUniAddress()
中你有以下行打印“n / aa”:
System.out.println(s);
答案 1 :(得分:0)
当执行toString()方法中的return语句时,将调用get *()方法。然后创建一个字符串并由toString()方法返回。
因此在计算从toString()返回的字符串时打印'n / aa',然后toString()方法返回字符串,main方法打印从toString()生成的输出。