Так у меня есть этот класс Java со следующими атрибутами с сеттеров и добытчиками и т.д.:Tokenizing в 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 я хочу, чтобы прочитать текстовый файл, разметить на мой Студент класс следующим образом:
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);
Edit: текстовый файл, я предположу, что для чтения выглядит так, где -999 является «прекратить читать и перейти к следующим данным» ограничитель.
Jones,Mary,903452
4342,2.5,A
3311,C
-999
Martin,Joseph,312345
4598,3,C
1122,3
-999
Я думал, что это возможно. Очевидно, это не так. Как я могу это сделать?
От комментариев в коде:
это проблема !!
Студент принимает во всех лексем, как струны, когда tempCourse является ArrayList<String>
'' Я думал, что это возможно. Очевидно, это не так. "' - на основе какой информации? Большинство зависит от структуры текстового файла, чего вы еще не показали нам. –
Ах часть вашего вопроса похоронена в комментариях - пожалуйста, не делайте этого. Поместите основное мясо вопроса, чтобы все могли его увидеть. –
Как хранится tempCourse в файле? Это текстовый файл? Пожалуйста, сделайте свой вопрос более полным, чтобы можно было ответить. –