问题描述
哎。你可能最近看到一个帖子被我寻求帮助,但我做到了以前错误的,所以我要重新开始,并在从基础教起。
Hey. You may have recently seen a post by me looking for help, but I did it wrong before, so I am going to start fresh and begin at the basics.
我想读的文本文件看起来像这样:
I am trying to read a text file that looks like this:
FTFFFTTFFTFT结果
3054 FTFFFTTFFTFT结果
4674 FTFTFFTTTFTF结果
...等
我需要做的就是把第一行成一个String作为答案的关键是什么。
What I need to do is put the first line into a String as the answer key.
接下来,我需要建立与学生证(第一号)的数组。
然后,我需要创建一个数组,它是平行于包含学生回答学生的ID。
Next, I need to create an array with the student ID (the first numbers).Then, I need to create an array that is parallel to the student ID that contains the student's answers.
下面是我的code,我不能完全弄清楚如何得到它像这样的工作,我想知道,如果有人可以帮助我了。
Below is my code, and I can't quite figure out how to get it to work like this, and I was wondering if someone could help me out 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;
}
因此,在一天结束时,该阵列结构应该是这样的:
So at the end of the day, the array structure should look like:
studentID [0] = 3054搜索
studentID [1] = 4674搜索
...等
studentID[0] = 3054
studentID[1] = 4674
... etc
studentAnswers [0] = FTFFFTTFFTFT结果
studentAnswers [1] = FTFTFFTTTFTF
studentAnswers[0] = FTFFFTTFFTFT
studentAnswers[1] = FTFTFFTTTFTF
感谢:)
推荐答案
假设你已经阅读(因为我看不到读者变量的初始化或阅读器的类型)正确打开的文件和内容(根据你所期望的)文件是良好的,你必须做到以下几点:
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++;
}
当然,如果你为了避免运行时错误的情况下(文件的内容是不正确的)添加一些检查,这将是最好的,例如周围的Integer.parseInt的try-catch子句()(可能会抛出NumberFormatException异常)。
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).
编辑:我刚才注意到您要使用的StringTokenizer你的标题,所以我编辑我的code(更换分裂法与StringTokenizer的)
I just notice in your title that you want to use StringTokenizer, so I edited my code (replaced the split method with the StringTokenizer).
这篇关于使用字符串标记设置创建数组了一个文本文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!