我将字段值 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 错误。有什么方法可以正确地将数组的长度设置为同一个类中的字段值吗?
最佳答案
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]
}
关于java - 如何将数组的长度设置为同一类中的字段值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40117170/