2010-01-31 59 views
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; 
    } 

所以在一天结束时,所述阵列结构应该是这样的:

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

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

谢谢:)

回答

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

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

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

2

你可能要考虑一下......

  • 使用Scanner类使用集合类型(如ArrayList)而不是原始阵列令牌化输入
  • - 阵列有其用途,但他们不太灵活;一个ArrayList具有动态长度
  • 创建一个类来封装的学生证和他们的答案 - 这保持信息一起,避免了需要保持两个阵列同步

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)); 
} 
相关问题