使用来自另一个类的输入

时间:2014-11-21 23:13:27

标签: java arrays

现在我有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();
        }   
    }

我想得到&#34; seatNum&#34;变量并使用它来创建rowA和rowB数组。我尝试了几件事:

  • 我在PassWagon课程中生成了随机数,但这次每个旅行车对象都会有不同数量的座位。我希望所有货车都有相同数量的座位。
  • 我在构造函数中创建了rowA和rowB数组,这次我无法在构造函数外部接受rowA和rowB数组。

    有人有什么想法吗?

1 个答案:

答案 0 :(得分: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