Using string tokenizer to set create arrays out of a text file?

一个人想着一个人 提交于 2019-12-01 20:31:43

Assuming you have opened the file correctly for reading (because I can't see how the reader variable is initialized or the type of the reader) and the contents of the file are well-formed (according to what you expect), you have to do the following:

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

Of course it would be best if you add some checks in order to avoid runtime errors (in case the contents of the file are not correct), e.g. try-catch clause around Integer.parseInt() (might throw NumberFormatException).

EDIT: I just notice in your title that you want to use StringTokenizer, so I edited my code (replaced the split method with the StringTokenizer).

You may want to think about...

  • using the Scanner class for tokenizing the input
  • using collection types (such as ArrayList) instead of raw arrays - arrays have their uses, but they aren't very flexible; an ArrayList has a dynamic length
  • creating a class to encapsulate the student id and their answers - this keeps the information together and avoids the need to keep two arrays in sync

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));
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!