将文本文件中的数据解析为 Java 中的多个数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7562093/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 20:31:23  来源:igfitidea点击:

Parsing data from text file into multiple arrays in Java

javaparsingfileinputstream

提问by LucRicher

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

首先让我说我对 Java 还很陌生,所以如果我犯了明显的错误,请原谅我......

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
courseName courseNumber creditHours grade
.
.

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
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.

第一行表示将列出并需要移动到数组的“学生”总数。第一个数组将包含学生信息,因此
studentName、studentID、numberOfCourses
为一个数组,而
courseName、courseNumber、creditHours、grade
为第二个数组。

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.

我的问题源于如何解析这些数据。
我目前正在阅读第一行,转换为 int 并使用它来确定我的学生数组的大小。在那之后,我不知道如何将数据移动到数组中,并让我的程序知道将哪些行移动到哪个数组中。

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.

需要注意的一件事是,每个学生学习的课程数量是可变的,所以我不能简单地将 1 行读入一个数组,然后将 3 行读入下一个,等等。

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.

我想从这一点上我遇到的主要问题是找出如何循环,将学生信息读取到学生数组,然后将课程信息读取到适当的课程数组位置,然后重新开始一个新的直到所有学生都读完。

采纳答案by Taha

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 studentsarray, after the execution of ParseStore


您可以students在执行后通过打印数组的内容来测试它ParseStore

回答by jornb87

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>

回答by Daniel Brockman

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);
}