开发者

Parsing data from text file into multiple arrays in Java

Let me start by saying I am fairly new to Java so forgive me if I am making obvious mistakes...

I have a text file that I must read data from and split the data into separate arrays.

The text file contains data in this format (although if necessary it can be slightly modified to have identifier tags if it is the only way)

noOfStudents

studentNAme studentID numberOfCourses

courseName courseNumber creditHours grade

courseName courseNumber creditHours grade

courseName courseNumber creditHours grade

.

.

studentNAme studentID numberOfCourses

courseName courseNumber creditHours grade

courseName courseNumber creditHours grade

开发者_Python百科 courseName courseNumber creditHours grade

.

.

The first line indicates the total number of "students" that will be listed and will need to be moved to arrays. One array will contain student information so

studentName, studentID, numberOfCourses

to one array, and

courseName, courseNumber, creditHours, grade

to the second array.

My problem is stemming from how to parse this data.

I'm currently reading in the first line, converting to int and using that to determine the size of my student array. After that I am at a loss for how to move the data into arrays and have my program know which array to move which lines into.

One thing to note is that the number of courses each student takes is variable so I can't simply read 1 line into one array, then 3 lines into the next, etc.

Will I need to use identifiers or am I missing something obvious? I've been looking at this problem for a week now and at this point I'm just getting frustrated.

Any help is greatly appreciated! thank you

edit: Here is the code section I am working on at the moment.

public static void main(String args[])
  {
  try{
  // Open the file
  FileInputStream fstream = new FileInputStream("a1.txt");
  // Get the object of DataInputStream
  DataInputStream in = new DataInputStream(fstream);
  BufferedReader br = new BufferedReader(new InputStreamReader(in));

  String strLine; // temporarily holds the characters from the current line being read
  String firstLine; // String to hold first line which is number of students total in     file.

  // Read firstLine, remove the , character, and convert the string to int value. 
  firstLine = br.readLine();
  firstLine = firstLine.replaceAll(", ", "");
  int regStudnt = Integer.parseInt(firstLine);
  // Just to test that number is being read correctly.
  System.out.println(regStudnt + " Number of students\n");

  // 2D array to hold student information
  String[][] students;
  // Array is initialized large enough to hold every student with 3 entries per student. 
  // Entries will be studentName, studentID, numberOfCourses
  students = new String[3][regStudnt];


  //Read File Line By Line
  while ((strLine = br.readLine()) != null)   {
      // Split each line into separate array entries via .split at indicator character.
      // temporary Array for this is named strArr and is rewriten over after every line   read.
      String[] strArr;
      strArr = strLine.split(", ");
  }

  //Close the input stream
  in.close();
    }catch (Exception e){//Catch exception if any
  System.err.println("Error: " + e.getMessage());
  }
  }

I hope this helps someone lead me in the right direction.

I guess the major problem I'm having from this point is finding out how to loop in such a way that the student info is read to the student array, then the course info to the appropriate course array location, then start again with a new student until all students have been read.


Give this code segment a try, I think its exactly according to your requirement. If you have any confusion do let me know!

class course {

        String name;
        int number;
        int credit;
        String grade;
    }

    class student {

        String name;
        String id;
        int numberCourses;
        course[] courses;
    }

    class ParseStore {

        student[] students;

        void initStudent(int len) {
            for (int i = 0; i < len; i++) {
                students[i] = new student();
            }
        }

        void initCourse(int index, int len) {
            for (int i = 0; i < len; i++) {
                students[index].courses[i] = new course();
            }
        }

        void parseFile() throws FileNotFoundException, IOException {
            FileInputStream fstream = new FileInputStream("test.txt");
            DataInputStream in = new DataInputStream(fstream);
            BufferedReader br = new BufferedReader(new InputStreamReader(in));

            int numberStudent = Integer.parseInt(br.readLine());
            students = new student[numberStudent];
            initStudent(numberStudent);

            for (int i = 0; i < numberStudent; i++) {

                String line = br.readLine();
                int numberCourse = Integer.parseInt(line.split(" ")[2]);
                students[i].name = line.split(" ")[0];
                students[i].id = line.split(" ")[1];
                students[i].numberCourses = numberCourse;
                students[i].courses = new course[numberCourse];
                initCourse(i, numberCourse);

                for (int j = 0; j < numberCourse; j++) {
                    line = br.readLine();
                    students[i].courses[j].name = line.split(" ")[0];
                    students[i].courses[j].number = Integer.parseInt(line.split(" ")[1]);
                    students[i].courses[j].credit = Integer.parseInt(line.split(" ")[2]);
                    students[i].courses[j].grade = line.split(" ")[3];
                }
            }                        
        }
    }


You may test it by printing the contents of students array, after the execution of ParseStore


Having an identifier (could be an empty line) for when a new student begins would make it easy, as you could just do

if("yourIdentifier".equals(yourReadLine))
    <your code for starting a new student>


Here is some pseudocode that should get you on track:

Student[] readFile() {
  int noOfStudents = ...;
  Student[] students = new Student[noOfStudents];

  for (int i = 0; i < noOfStudents; ++i) {
    students[i] = readStudent();
  }

  return students;
}

Student readStudent() {
  int numberOfCourses = ...;
  String name = ...;
  String id = ...;

  Course[] courses = new Course[numberOfCourses]

  for (int i = 0; i < numberOfCourses; ++i) {
    courses[i] = readCourse();
  }

  return new Student(id, name, courses);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜