所以我有了这个Java类,它有以下属性,包括setter和getter等:
public class Student implements Comparable<Student> {
//Student attributes
protected String firstName;
protected String lastName;
protected String major;
protected String idNo;
protected ArrayList<String> courseTaken;
protected int credits;
protected double grade;
public Student(){
}
//constructor
public Student(String firstName, String lastName, String major, String idNo, ArrayList<String> courseTaken, int credits, double grade)
{
this.firstName = firstName;
this.lastName = lastName;
this.major = major;
this.idNo = idNo;
this.courseTaken = courseTaken;
this.credits = credits;
this.grade = grade;
}
在main。java中,我想读取一个txt文件,将其标记为Student类,如下所示:
List<Student> students = new ArrayList<>();
try
{
// create a Buffered Reader object instance with a FileReader
BufferedReader br = new BufferedReader(new FileReader("file.txt"));
// read the first line from the text file
String fileRead = br.readLine();
// loop until all lines are read
while (fileRead != null)
{
// use string.split to load a string array with the values from each line of
// the file, using a comma as the delimiter
String[] tokenize = fileRead.split(",");
// assume file is made correctly
// and make temporary variables for the seven types of data
String tempFirstN= tokenize[0];
String tempLastN = tokenize[1];
String tempMajor = tokenize[2];
String tempIdNo = tokenize[3];
String tempCourse = tokenize[4];
int tempCredits = Integer.parseInt(tokenize[5]);
double tempGpa = Double.parseDouble(tokenize[6]);
// create temporary instance of Student object
// and load with three data values
/**this is the problem!!
*
* Student takes in all tokens as Strings when tempCourse is an ArrayList<String>
*
**/
Student tempStudent = new Student(tempFirstN, tempLastN, tempMajor, tempIdNo, tempCourse, tempCredits, tempGpa);
// add to array list
students.add(tempStudent);
编辑:我想要读取的文本文件看起来像这样,其中-999是"停止读取并转到下一个数据"限制符。
Jones,Mary,903452
4342,2.5,A
3311,C
-999
Martin,Joseph,312345
4598,3,C
1122,3
-999
我认为这是可能的。显然不是。我该怎么做呢?
来自代码注释:
这就是问题所在!!
当tempCourse为ArrayList<String>
您遇到的问题是解析代码与文件中的数据根本不匹配。您似乎试图读取所有数据,就好像它在一行上一样,然后将其分开,好像这一行包含7个令牌:
String[] tokenize = fileRead.split(",");
String tempFirstN= tokenize[0];
String tempLastN = tokenize[1];
String tempMajor = tokenize[2];
String tempIdNo = tokenize[3];
String tempCourse = tokenize[4];
int tempCredits = Integer.parseInt(tokenize[5]);
double tempGpa = Double.parseDouble(tokenize[6]); // !! 7 tokens !!
但是你的文件根本不是这样构造的:
Jones,Mary,903452
4342,2.5,A
3311,C
-999
Martin,Joseph,312345
4598,3,C
1122,3
-999
更确切地说,似乎文件表示中的每个Student都包含几行,实际上是一个可变的数字,第一行只包含3个标记,第二行(可能)包含3个,然后任何人都可以猜测接下来的行显示什么。
要解决这个问题,您必须完全理解文件结构,然后相应地更改解析代码,包括使用内部循环读取文本,直到出现"-999"。
tempCourse
是一个字符串,但在构造函数中,您期望ArrayList<String>
为courseTaken。显然这是行不通的(没有从单个对象到这些对象的数组列表的自动转换)。
你要么必须使这个字段和构造函数参数为String(因此每个学生正好有一个课程),要么将tempCourse标记拆分为单独的String(使用另一个额外的分隔符,例如分号),将它们填充到ArrayList中并将该ArrayList传递给构造函数