如何在同一个类中将数组长度设置为字段值?

0 java arrays field

我将字段值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);
}
Run Code Online (Sandbox Code Playgroud)

其他课程:

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

我希望fieldArray字段具有maxSeats的长度,但似乎这将数组的长度设置为0,并且我得到了outofboudary错误.有没有办法将数组的长度正确设置为同一类中的字段值?

Zir*_*con 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]
}
Run Code Online (Sandbox Code Playgroud)