我正在尝试使用scanner加载模块的ArrayList,然后每个模块还包含为该模块注册的StudentsList。这是我的模块的构造函数:
public Module(String newCode, ArrayList<Student> students){
}
要从文本文件中加载数据,如下所示:
5 (number of modules)
CS10110 (module code)
2 (number of students enrolled in the above module)
fyb9 (student enrolled)
lfr8 (student enrolled)
CS10310
0
CS12130
1
fyb9
CS12230
1
lfr8
CS10610
2
fyb9
lfr8
我已经能够使用扫描仪加载这样的学生:
public void loadStudents(String fileName) throws FileNotFoundException{
Scanner infile =new Scanner(new InputStreamReader
(new FileInputStream(fileName)));
int num=infile.nextInt();infile.nextLine();
for (int i=0;i<num;i++) {
String u=infile.nextLine();
String s=infile.nextLine();
String n=infile.nextLine();
String c=infile.nextLine();
Student st = new Student(u,s,n,c);
students.add(st);
}
infile.close();
}
但我正在努力加载其中包含ArrayLists的ArrayList,这就是我目前的粗略代码:
public void loadModules(String fileName) throws FileNotFoundException{
Scanner infile =new Scanner(new InputStreamReader
(new FileInputStream(fileName)));
int num=infile.nextInt();infile.nextLine();
for (int i=0;i<num;i++){
String c=infile.nextLine();
ArrayList<Student> a =infile.next();
Module m = new Module(c,a);
但显然这不起作用。任何想法或提示将受到高度赞赏
答案 0 :(得分:1)
infile.next()
会返回String
值,因此无法填充ArrayList<Student>
。从文本文件填充ArrayList<ArrayList<String>>
的一般方法可能如下:
public ArrayList<ArrayList<String>> readFile(String filename) throws IOException
{
FileInputStream fis = new FileInputStream(filename);
Scanner sc = new Scanner(fis);
ArrayList<ArrayList<String>> modulesList = new ArrayList<>();
int numModules = sc.nextInt();
for (int i = 0; i < numModules; i++)
{
int numStringsPerModule = sc.nextInt();
ArrayList<String> moduleEntries = new ArrayList<>();
for (int j = 0; j < numStringsPerModule; j++)
{
String entry = sc.next();
moduleEntries.add(entry);
}
modulesList.add(moduleEntries);
}
return modulesList;
}
您应该能够根据您的具体情况定制此代码。一般的想法是你需要使用嵌套的for
循环,内部循环读取在一个模块中。
答案 1 :(得分:0)
以下情况如何?
public ArrayList<Student> loadStudents(Scanner infile) throws FileNotFoundException{
ArrayList<Student> students = new ArrayList<Student>();
int num=infile.nextInt();infile.nextLine();
for (int i=0;i<num;i++) {
String u=infile.nextLine();
String s=infile.nextLine();
String n=infile.nextLine();
String c=infile.nextLine();
Student st = new Student(u,s,n,c);
students.add(st);
}
return studtends;
}
和
public List<Module> loadModules(String fileName) throws FileNotFoundException{
Scanner infile =new Scanner(new InputStreamReader
(new FileInputStream(fileName)));
int num=infile.nextInt();infile.nextLine();
List<Module> ret = List<Module>();
for (int i=0;i<num;i++){
String c=infile.nextLine();
ArrayList<Student> a =loadStudents(infile);
Module m = new Module(c,a);
ret.add(m);
}
infile.close();
return ret;
}
使用List,Module构造函数会更好。如果可能,请不要在接口中使用实现。