问题
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
... etc
What I need to do is put the first line into a String as the answer key.
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.
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
... etc
studentAnswers[0] = FTFFFTTFFTFT
studentAnswers[1] = FTFTFFTTTFTF
Thanks :)
回答1:
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).
回答2:
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));
}
来源:https://stackoverflow.com/questions/2173855/using-string-tokenizer-to-set-create-arrays-out-of-a-text-file