首先让我说我对 Java 还很陌生,如果我犯了明显的错误,请原谅我......
我有一个文本文件,我必须从中读取数据并将数据拆分为单独的数组。
文本文件包含这种格式的数据(如果必要的话,如果它是唯一的方法,可以稍微修改它以具有标识符标签)
noOfStudents
studentNAME 学生 ID numberOfCourses
courseName courseNumber creditHours Grade
courseName courseNumber creditHours Grade
courseName courseNumber creditHours Grade
。
.
studentName studentID numberOfCourses
courseName courseNumber creditHours Grade
courseName courseNumber creditHours Grade
courseName courseNumber creditHours Grade
。
.
第一行表示将列出并需要移动到数组中的“学生”总数。一个数组将包含学生信息,因此
studentName、studentID、numberOfCourses将包含
在一个数组中,而
courseName、courseNumber、creditHours、grade
将包含在第二个数组中。
我的问题源于如何解析这些数据。
我目前正在阅读第一行,转换为 int 并使用它来确定我的学生数组的大小。之后,我不知道如何将数据移动到数组中,并让我的程序知道将哪些行移动到哪个数组中。
需要注意的一点是,每个学生学习的课程数量是可变的,所以我不能简单地将 1 行读入一个数组,然后将 3 行读入下一个数组,等等。
我需要使用标识符还是遗漏了一些明显的东西?我已经研究这个问题一个星期了,此时我只是感到沮丧。
任何帮助是极大的赞赏!谢谢你
编辑:这是我目前正在处理的代码部分。
public static void main(String args[])
{
try{
// Open the file
FileInputStream fstream = new FileInputStream("a1.txt");
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine; // temporarily holds the characters from the current line being read
String firstLine; // String to hold first line which is number of students total in file.
// Read firstLine, remove the , character, and convert the string to int value.
firstLine = br.readLine();
firstLine = firstLine.replaceAll(", ", "");
int regStudnt = Integer.parseInt(firstLine);
// Just to test that number is being read correctly.
System.out.println(regStudnt + " Number of students\n");
// 2D array to hold student information
String[][] students;
// Array is initialized large enough to hold every student with 3 entries per student.
// Entries will be studentName, studentID, numberOfCourses
students = new String[3][regStudnt];
//Read File Line By Line
while ((strLine = br.readLine()) != null) {
// Split each line into separate array entries via .split at indicator character.
// temporary Array for this is named strArr and is rewriten over after every line read.
String[] strArr;
strArr = strLine.split(", ");
}
//Close the input stream
in.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
我希望这可以帮助有人引导我朝着正确的方向前进。
我想我从这一点开始遇到的主要问题是找出如何循环,将学生信息读取到学生数组,然后将课程信息读取到适当的课程数组位置,然后重新开始学生,直到所有学生都读完为止。