2014-11-21 203 views
0

現在我有3個類。火車,旅行車和乘客。在火車類使用來自其他類的輸入

public class Train 
    { 
     private int seatNum = 30 + (int) (Math.random() * ((40 - 30) + 1)); //Random number of seats 
     private int wagonNum = 5 + (int) (Math.random() * ((10 - 5) + 1));//Random number of wagons 

     public Train() 
     { 
      PassWagon[] wagons = new PassWagon[wagonNum];//here I created an array with random wagon numbers. 

      for (int i = 0; i < wagonNum; i++) 
      { 
       wagons[i] = new PassWagon(seatNum); // I added PassWagon objects to that array. I need to access "seatnum" in the PassWagon class. 

      } 
     } 

    } 

public class PassWagon 
{ 
private int wagonseats ; 

Passenger[] rowA = new Passenger[wagonseats]; //I created 2 "Passenger" arrays. Problem is, wagonseats variable has nothing. "seatNum" variable from other class gets initiated at Constructor. 
Passenger[] rowB = new Passenger[wagonseats]; 
    public PassWagon(int seat) 
    { 
     this.wagonseats = seat; 

     for (int i = 0; i < seats; i++) 
     { 
      rowA[i] = new Passenger(); //I get an out of bounds error here because this array has nothing in it. 
      rowB[i] = new Passenger(); 
     } 
    } 

我想要得到的 「seatNum」 變量並使用它來創建行rowA和rowB中的陣列。我嘗試過幾件事:

  • 我在PassWagon類中生成了隨機數,但是這次每個貨車對象都有不同數量的座位。我希望所有的貨車都有相同數量的座位。
  • 我在構造函數裏面創建了rowA和rowB數組,這次我無法在構造函數外聲明rowA和rowB數組。

    有沒有人有任何想法?

回答

1

你應該創建rowArowB變量領域,構造之外,但是初始化他們在構造函數中,一旦你的參數seat(實際上是席位法官數量來自其他班級)。

public class PassWagon { 
    private int wagonseats ; 

    Passenger[] rowA; // Just create, don't initialize yet 
    Passenger[] rowB; 

    public PassWagon(int seat) { 
     this.wagonseats = seat; 
     rowA = new Passenger[wagonseats]; 
     rowB = new Passenger[wagonseats]; 

     for (int i = 0; i < wagonseats; i++) { 
      rowA[i] = new Passenger(); 
      rowB[i] = new Passenger(); 
     } 
    } 
} 

你的問題是,當你在構造函數之前初始化它們,wagonseats剛剛創建的,因此包含0。所以你正在創建一個零成員數組。創建後無法更改,因此只有在擁有正確的編號時才能創建它。

順便說一下,如果有兩排,我想wagonseats實際上應該是seat/2,不是嗎?或者至少,陣列的大小和循環的極限應該是seat/2