我很困惑,爲什麼我的程序按特定順序打印語句?內部類 - 打印語句的順序 -
我有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類(與主方法)
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()
方法),那麼我很好奇,至於爲什麼在方法toString()
之前會打印getUniAddress()方法中的'n/aa'? (如上)
如果我做調用setUniAddress()方法進行的說就是:
NAME: Cathy
HOME ADDRESS: 21 Smithfield Drive
TERM TIME ADDRESS: 72 Nottingham Drive
(all on new lines)
這似乎按預期方式工作。
我也想知道的不是打印「空」到TERM時間地址如何:(當不叫setUniAddress()
方法),我可能會返回「N/A」代替它 - 這是我正在嘗試做什麼?
謝謝。
這是有效的代碼嗎? 'String homeStreet; homeAddress = new Address(houseNumber,homeStreet);' 對我來說這看起來很奇怪。 – bbalchev
這對我來說都是新鮮事,這是我第一次嘗試內部課程 –
@bbalchev在同一行寫兩條語句並不好,但它非常有效。也就是說,我在OP發佈的代碼中找不到類似的東西。 – alfasin