使用字符串标记生成器从文本文件中设置创建数组?

嘿。 您可能最近看到我寻找帮助的post,但我之前做错了,所以我将重新开始并从基础开始。

我试图读取一个看起来像这样的文本文件:

FTFFFTTFFTFT
3054 FTFFFTTFFTFT
4674 FTFTFFTTTFTF
……等

我需要做的是将第一行放入String作为答案键。

接下来,我需要创建一个包含学生ID(第一个数字)的数组。 然后,我需要创建一个与包含学生答案的学生ID平行的数组。

下面是我的代码,我无法弄清楚如何让它像这样工作,我想知道是否有人可以帮助我。

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

谢谢 :)

假设您已正确打开文件进行读取(因为我无法看到读取器变量的初始化方式或读取器的类型),并且文件内容格式正确(根据您的期望),您必须请执行下列操作:

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

当然最好是添加一些检查以避免运行时错误(如果文件内容不正确),例如Integer.parseInt()周围的try-catch子句(可能抛出NumberFormatException)。

编辑:我只是在你的标题中注意到你想使用StringTokenizer,所以我编辑了我的代码(用StringTokenizer替换了split方法)。

你可能想要考虑……

  • 使用Scanner类来标记输入
  • 使用集合类型(例如ArrayList )而不是原始数组 – 数组有它们的用途,但它们不是很灵活; ArrayList具有动态长度
  • 创建一个类来封装学生ID及其答案 – 这可以将信息保存在一起,避免了保持两个数组同步的需要

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