3

嘿。您可能最近看到了我寻求帮助的帖子,但我之前做错了,所以我要重新开始,从基础开始。

我正在尝试读取如下所示的文本文件:

FTFFFTTFFTFT
3054 FTFFFTTFFTFT
4674 FTFTFFTTTFTF
...等

我需要做的是将第一行放入一个字符串作为答案键。

接下来,我需要使用学生 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;
    }

所以归根结底,数组结构应该如下所示:

学生ID[0] = 3054
学生ID[1] = 4674
...等

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

谢谢 :)

4

2 回答 2

2

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

  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 方法)。

于 2010-02-01T00:16:51.000 回答
2

你可能要考虑...

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

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));
}
于 2010-02-01T10:26:15.637 回答