此代码中有一个错误,我无法使用oop将数组列表分配给数组,也无法找到解决方法! 我将我的代码和类放在这里,以便任何人都可以帮助我找出问题所在!!!
package java808session06app04classnumber03;
import java.util.ArrayList;
import java.util.Scanner;
public class Java808session06app04classnumber03 {
public static void main(String[] args) {
final int SCHOOL_CLASS_NUMBER = 3;
Scanner user = new Scanner(System.in);
SchoolClass[] schoolClassArray = new SchoolClass[SCHOOL_CLASS_NUMBER];
int intNextStudent = 1;
int intAvg = 0;
for (int i = 0; i < SCHOOL_CLASS_NUMBER; i++) {
System.out.println("Class " + (i + 1) + ": ");
do {
ArrayList<Student> studentList = new ArrayList<>();
Student st01 = new Student();
System.out.print("Enter student name: ");
st01._name = user.next();
System.out.print("Enter student family: ");
st01._family = user.next();
System.out.print("Enter student grade01: ");
st01._grade01 = user.nextInt();
System.out.print("Enter student grade02: ");
st01._grade02 = user.nextInt();
System.out.print("Enter student grade03: ");
st01._grade03 = user.nextInt();
System.out.print("Enter student grade04: ");
st01._grade04 = user.nextInt();
studentList.add(st01);
System.out.print("Is next student (1 for next student): ");
intNextStudent = user.nextInt();
schoolClassArray[i].studentList = studentList;
} while (intNextStudent == 1);
}
}
}
这些是我为这段代码制作的类!
班级School
{
ArrayList<Student> studentList = new ArrayList<>();
}
班级学生
{
String _name;
String _family;
int _grade01;
int _grade02;
int _grade03;
int _grade04;
}
答案 0 :(得分:3)
您忘了初始化数组中的SchoolClass
。
紧接着
for (int i = 0; i < SCHOOL_CLASS_NUMBER; i++) {
插入一行:
schoolClassArray[i] = new SchoolClass();
答案 1 :(得分:0)
我不确定您要使用提供的代码做什么。我发现您的代码中有1个潜在错误,在do
循环的开始,您在每次迭代中都创建了一个新的ArrayList
,因此应将其移出do循环。
对于ArrayList
至Array
部分,您可以执行类似以下操作(Source):
List<String> list = new ArrayList<String>();
list.add("India");
list.add("Switzerland");
String [] countries = list.toArray(new String[list.size()]);