2016-10-18 70 views
0

我將字段值maxSeats設置爲表示將會像這樣在主類中的最大座位數。 主類:如何將數組的長度設置爲同一個類中的字段值?

public static void main(String[] args) { 
    Student a = new Student("Abigail", 1, 5); 
    Student b = new Student("Benny", 1, 6); 
    Student c = new Student("Charles", 1, 10); 
    Student d = new Student("Denise", 2, 12); 
    Student e = new Student("Eleanor", 2, 9); 
    Student f = new Student("Fred", 2, 5); 

    SchoolBus sb1 = new SchoolBus(3, 1); 
    SchoolBus sb2 = new SchoolBus(3, 2); 
    sb1.getRemainSeat(); 
    sb1.addStudent("Benny", 1, 6); 
} 

其他類:

private int maxSeats; 
private int routeNum; 
String[] studentArray = new String[3]; 
public SchoolBus(int mS, int rN){ 
    mS = maxSeats; 
    rN = routeNum; 
} 

而且我要現場studentArray有maxSeats的長度,但似乎這臺數組的長度爲0,和我得到outofboudary錯誤。有什麼方法可以將數組的長度正確設置爲同一個類中的字段值?

+0

您的意思是做'maxSeats = MS;'和'routeNum = RN;'? –

回答

0

是這樣的?

String[] studentArray ; 
public SchoolBus(int mS, int rN){ 
    mS = maxSeats;// this it the wrong way around 
    maxSeats= mS; // this ist the way to go! 
    rN = routeNum; 
    studentArray = new String[mS]; 
} 
5

1)您需要在定義變量值maxSeats後創建數組。

2)您正在向後設置構造函數中的值。

試試這個:

private int maxSeats; 
private int routeNum; 
String[] studentArray; 
public SchoolBus(int mS, int rN){ 
    maxSeats = mS; 
    routeNum = rN; 
    studentArray = new String[maxSeats]; //Define an array of length [maxSeats] 
} 
相關問題