[英]Java Load in an ArrayList of ArrayList using scanner
我正在嘗試使用掃描儀加載模塊ArrayList,然后每個模塊還包含針對該模塊注冊的Student ArrayList。 這是我的模塊構造函數:
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);
但這顯然行不通。 這里的任何想法或技巧將不勝感激
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
循環,並且將內部循環讀入單個模塊中。
接下來呢?
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構造函數。 如果可能,不要在接口中使用實現。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.