Using a string tokenizer to set arrays from a text file?

Hey. You may have recently seen a message from me looking for help, but I used to do it wrong, so I'm going to start a new job and start with the basics.

I am trying to read a text file that looks like this:

FTFFFTTFFTFT
3054 FTFFFTTFFTFT
4674 FTFTFFTTTFTF
... etc.

What I need to do is put the first line in the line as the response key.

Next, I need to create an array with the student ID (first numbers). Then I need to create an array parallel to the student ID that contains the student's answers.

Below is my code, and I cannot figure out how to make it work like this, and I was wondering if anyone could help me with it.

public static String[] getData() throws IOException {
      int[] studentID = new int[50];
      String[] studentAnswers = new String[50];
      int total = 0;

      String line = reader.readLine();
      strTkn = new StringTokenizer(line);
      String answerKey = strTkn.nextToken();

      while(line != null) {
        studentID[total] = Integer.parseInt(strTkn.nextToken());
        studentAnswers[total] = strTkn.nextToken();
        total++;
      }
    return studentAnswers;
    }

, :

studentID [0] = 3054
studentID [1] = 4674
... ..

studentAnswers [0] = FTFFFTTFFTFT
studentAnswers [1] = FTFTFFTTTFTF

:)

+3
2

, ( , ), ( , ) :

  String line = reader.readLine();
  String answerKey = line;
  StringTokenizer tokens;
  while((line = reader.readLine()) != null) {
    tokens = new StringTokenizer(line);
    studentID[total] = Integer.parseInt(tokens.nextToken());
    studentAnswers[total] = tokens.nextToken();
    total++;
  }

, , , ( , ), . try-catch Integer.parseInt() ( NumberFormatException).

EDIT: , StringTokenizer, ( split StringTokenizer).

+2

, ...


Scanner input = new Scanner(new File("scan.txt"), "UTF-8");
List<AnswerRecord> test = new ArrayList<AnswerRecord>();
String answerKey = input.next();
while (input.hasNext()) {
  int id = input.nextInt();
  String answers = input.next();
  test.add(new AnswerRecord(id, answers));
}
+2

Source: https://habr.com/ru/post/1730798/


All Articles