java - 如何将数组的长度设置为同一类中的字段值?

标签 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);
}

其他类:

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/

相关文章:

java - 与字符串的合并排序

java - 使用 Java 8 lambda 表达式打印有关错误的调试信息

arrays - 将 JSON 对象列表解码为 perl 中的哈希数组

json - 避免从表行构建的 JSON 中的匿名字段

java - Hibernate - 遍历 createSQLQuery 结果并读入适当的对象

Java:关于 JLS 中解释的 Java 关键字 "volatile"的混淆

python - 在Python中定义数组类型由C函数填充

python - 如何在循环内对数组进行列堆栈?

mysql - 拆分sql查询中的字段并按它们排序

c# - 基于 .Net 中的字段反序列化 json (C#)