I’m reading in data from different txt files to make objects and then into arraylists of the objects.
just as an example I have a teacher class with 3 or 4 varibles
public class Teacher {
public static String teacherNo;
public static String firstName;
public static String lastName;
public static Courses coursestought;
and a class Courses
public class Course {
public static String cCode;
public static String cName;
the constructor for the teacher class is like this
// constructor
public Teacher(String teacher_No,String first_Name,String last_Name,
Course coursesTought,)
I have all the right getters and setters(I think)
I read from the text file like this.
BufferedReader inFile = new BufferedReader (new FileReader
("pathtofile/teachers.txt"));
And I create the Teacher objects like this
String inputLine;
inputLine = inFile.readLine();
while (inputLine != null)
{
teacherlist.add(new Teacher
(inputLine, inputLine, inputLine, inputLine,));
inputLine = inFile.readLine();
}
But this only works if all the fields are strings not a mix of strings and variables and objects. The fields in the text file are 1 line to a teacher and separated by :
Can someone point me in the right direction here?
Do I need to cut up the strings as I read them in ?
Yes. You need to use String#split() to split the strings once you read them, create your objects and then add them to your arraylist
Not very clear from your question how the
Coursesobject is represented in your text file. If thats variable length on the same line, you might have to do some additional magic to dynamically create theCoursesobject and then create theTeacherobject.Your instance variables inside class
TeacherandCoursesshould not be static either. Static means class level and not object level.If you have a Teacher class that looks like this ,
then, you could call it like this within your while loop —
This is assuming your teacher line in text has a course code and course name as part of it.