【发布时间】:2016-03-13 08:47:37
【问题描述】:
所以我试图通读整个文件并打印它的内容,它确实如此。但是当我用新的扫描仪再次检查它以打印带有一些部分名称的内容时,它只会检查一些文件。
这是我的代码:
import java.util.*;
import java.io.*;
public class FileReader {
public static void main(String[] args) throws FileNotFoundException {
Scanner read = new Scanner(new File("sample.txt"));
while(read.hasNextLine()) {
System.out.println(read.nextLine());
}
System.out.println();
Scanner read2 = new Scanner(new File("sample.txt"));
int numQuestions = read2.nextInt();
System.out.println("Numbers of questions: " + numQuestions);
System.out.println();
while(read2.hasNextLine()) {
int points, numChoices;
String question, answer;
if(read2.next().equals("TF")) {
points = read2.nextInt();
System.out.println("Points for TF: " + points);
read2.nextLine(); // must be done because it does not consume the \n character
question = read2.nextLine();
System.out.println("Question for TF: " + question);
answer = read2.next();
System.out.println("Answer for TF: " + answer);
}
else if(read2.next().equals("SA")) {
points = read2.nextInt();
System.out.println("Points for SA: " + points);
read2.nextLine(); // must be done because it does not consume the \n character
question = read2.nextLine();
System.out.println("Question for SA: " + question);
answer = read2.next();
System.out.println("Answer for SA: " + answer);
}
else if(read2.next().equals("MC")) {
points = read2.nextInt();
System.out.println("Points for MC: " + points);
read2.nextLine(); // must be done because it does not consume the \n character
question = read2.nextLine();
System.out.println("Question for MC: " + question);
read2.nextLine();
numChoices = read2.nextInt();
for(int i = 0; i < numChoices; i++) {
System.out.println(read2.nextLine());
}
answer = read2.next();
System.out.println("Answer for MC: " + answer);
}
}
}
}
这是我正在读取的文件:
3
TF 5
There exist birds that can not fly. (true/false)
true
MC 10
Who was the president of the USA in 1991?
6
Richard Nixon
Gerald Ford
Jimmy Carter
Ronald Reagan
George Bush Sr.
Bill Clinton
E
SA 20
What city hosted the 2004 Summer Olympics?
Athens
这是我得到的输出:
3
TF 5
There exist birds that can not fly. (true/false)
true
MC 10
Who was the president of the USA in 1991?
6
Richard Nixon
Gerald Ford
Jimmy Carter
Ronald Reagan
George Bush Sr.
Bill Clinton
E
SA 20
What city hosted the 2004 Summer Olympics?
Athens
Numbers of questions: 3
Points for TF: 5
Question for TF: There exist birds that can not fly. (true/false)
Answer for TF: true
如您所见,第一个Scanner 读取整个文件并打印出来。但是当我第二次尝试使用部分名称时,它只通过问题 1 的部分。
【问题讨论】:
-
您只使用一次
Scanner read,然后创建第二个Scanner read2类型的对象。如果您不再需要read,您应该使用相同的变量来创建新的扫描器对象:read=new Scanner(new File("sample.txt"));。在这种情况下,变量更少,代码更易于阅读。
标签: java file java.util.scanner