所以我有這個Java類與getter和setter方法等下列屬性的ArrayList屬性:符號化構造
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文件,標記化到我的學生類,像這樣:
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>
''我認爲這是可能的,顯然它不是。「' - 基於什麼信息?大部分取決於文本文件的結構,這是您尚未向我們顯示的內容。 –
你的問題的一部分被埋在評論中 - 請不要這樣做。把問題的主要內容提供給所有人看。 –
tempCourse如何存儲在文件中?它是一個文本文件嗎?請讓你的問題更完整,以便能夠回答。 –