现在我有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数组。

有人有什么想法吗?

最佳答案

您应该在构造函数之外将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

07-24 22:18