我在 Java 中读取文件时遇到了一些问题。
文件是什么样子的:
Answer 1:
1. This is an apple
2. Something
Answer 2:
1. This is a cool website
2. I love banana
3. This is a table
4. Programming is fun
Answer 3.
1. Hello World
....
我想要做的是将它们分成两项:一项是答案编号;另一个是答案列表。
因此,假设我有一个名为 Answer: String of answer number List of answers 的对象类。
到目前为止,这是我在将代码放入对象类之前调试代码所做的工作。但我无法得到正确的结果
public void reader(String file) throws FileNotFoundException, IOException {
FileReader fR = new FileReader(file);
BufferedReader bR = new BufferedReader(fR);
String line = null;
int count = 0 ;
String blockNum = "";
String printState = "" ;
while ((line = bR.readLine()) != null) {
if(line.contains("Answer")){
//System.out.println("Contain Answer statement: " + line);
count++;
blockNum = line;
printState = "";
}
else{
//System.out.println("No Answer Statement: " + line);
printState += line + " / " ;
}
System.out.println( count + " " + blockNum + " " + printState );
}
// Close the input stream
bR.close();
fR.close();
}
我很确定我在编码时做了一些愚蠢的事情。我不太确定如何阅读它,以便将它分开。
现在输出如下所示:
1 Answer 1:
1 Answer 1: 1. This is an apple /
1 Answer 1: 1. This is an apple / 2. Something /
2 Answer 2:
2 Answer 2: 1. This is a cool website /
2 Answer 2: 1. This is a cool website / 2. I love banana /
2 Answer 2: 1. This is a cool website / 2. I love banana / 3. This is a table /
2 Answer 2: 1. This is a cool website / 2. I love banana / 3. This is a table / 4. Programming is fun /
3 Answer 3.
3 Answer 3. 1. Hello World /
但我希望输出是这样的:
1 Answer 1: 1. This is an apple / 2. Something /
2 Answer 2: 1. This is a cool website / 2. I love banana / 3. This is a table / 4. Programming is fun /
3 Answer 3. 1. Hello World /