Harry Lewis Harry Lewis - 6 months ago 11
Java Question

How do I read this text file into the following class array?

I have a class Student and two children classes, CasualStudent and PermanentStudent. I am doing this right now.

Employee[] a = new Employee[10];
int count;
a[0] = new PermanentStudent("John", "LUI", "HJFDDFDFJ");
a[1] = new PermanentStudent("Peter", "VAMPLEW", "VAM12345678");
a[2] = new PermanentStudent("Rudi", "SKACEL", "SKA51515151");
a[3] = new CasualStudent("Katie","BLACKBURN","BLA41925612");
a[4] = new CasualStudent("Neal","STEPHENSON","STE97527467");
a[5] = new CasualStudent("Neneh","CHERRY","CHE98765432");
a[6] = new CasualStudent("Chris","BROOKMYRE","BRO97635198");
a[7] = new CasualStudent("Grace","HOPPER","HOP26554432");
a[8] = new CasualStudent("Randall","MUNROE","XKCD1234567");
a[9] = new CasualStudent("Kaylee","FRYE","FRY90224718");


Each of these children classes have a constructor and I have manually coded the data in the code. Now, I want to read this data from a .txt file. I know how to read and I have done this till now:

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class Program {
public static void main(String[] args) {

BufferedReader reader = new BufferedReader(new FileReader(
"file.txt"));
while (true) {
String line = reader.readLine();
if (line == null) {
break;
}
System.out.println(line);
}
reader.close();
}
}


But how do I read the data into the classes like this? I am new to Java and I am not able to understand how to do this? Please guide me in the right direction. Thanks!

Also, the text file will always contain 10 lines and each line will have the following format.

John LUI HJFDDFDFJ
..................


Code:

61. int i = 0;
62. for (i = 0; i < 10; i++)
63. {
64. String x = a[i].toString();
65. System.out.println(x);
66. }

Answer

The simplest way would be as follows:

Employee[] employees = new Employee[10];
try (BufferedReader reader = new BufferedReader(new FileReader("file.txt"))) {

  for (int i = 0; i < 3; i++) {
    String line = reader.readLine();
    String[] parts = line.split(" ");
    employees[i] = new PermanentStudent(parts[0], parts[1], parts[2])
  }

  for (int i = 3; i < 10; i++) {
    String line = reader.readLine();
    String[] parts = line.split(" ");
    employees[i] = new CasualStudent(parts[0], parts[1], parts[2])
  }
}