gpt4 book ai didi

java - 在java中读取文件时遇到问题

转载 作者:行者123 更新时间:2023-12-01 07:37:00 25 4
gpt4 key购买 nike

我在用 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 的对象类:答案编号字符串答案列表。

这就是我迄今为止在将代码放入对象类之前调试代码所做的事情。但我无法得到正确的结果

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 /

最佳答案

您正在为您读取的每一行输入打印一行输出。尝试将 println 移动到检查答案的循环部分内,以确保仅打印每个答案/答案值集一次。例如:

if(line.contains("Answer")) {
if (printState != "") {
System.out.println(count + " " + blockNum + " " + printState);
}
...
}

编辑:退出 while 循环时您还需要进行打印,以确保打印最后一个答案/答案值集。

关于java - 在java中读取文件时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10556695/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com