gpt4 book ai didi

java - BufferReader程序逐行倒序打印输入文件(文本文件),但它也倒序打印单词

转载 作者:行者123 更新时间:2023-11-30 11:05:26 25 4
gpt4 key购买 nike

public static void main(String[] args) {
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader("C://Users/ALAN/Desktop/mary.txt"));
String lines = br.readLine();
ArrayList<String> buffer = new ArrayList<String>();
while (lines != null) {
if (lines != null) {
buffer.add("\n");
StringBuilder str = new StringBuilder();
String[] splitStr = lines.split(" ");
for (int i = splitStr.length; i > 0; i--) {
str.append(splitStr[i - 1]).append(" ");
}
buffer.add(str.toString());
}
lines = br.readLine();
}
for(int i = buffer.size() - 1; i > 0; i--) {
System.out.print(buffer.get(i));
}
br.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null) br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}

如何让我的程序逐行反向打印我的文本文件,但不让它反转单词。

例如,我有一个输出:

reply. did teacher the 23 
know." you lamb, the loves Mary "Why, 22
21
cry. children eager the 20

代替

23 the teacher did reply.
22 "Why, Mary loves the lamb, you know."
21
20 the eager children cry.

最佳答案

这从 splitStr.length 到 1 降序计数:

for (int i = splitStr.length; i > 0; i--) {
str.append(splitStr[i - 1]).append(" ");
}

因此,您正在以相反的顺序迭代 splitStr 数组。

下面的代码将以新月(非反向)顺序迭代,从 0 计数到小于 splitStr.length:

for (int i = 0; i < splitStr.length; i++) {
str.append(splitStr[i]).append(" ");
}

或者你可以简单地写:

for (String element : splitStr) {
str.append(element).append(" ");
}

同样适用于循环迭代buffer:

for (int i = buffer.size() - 1; i > 0; i--) {
System.out.print(buffer.get(i));
}

关于java - BufferReader程序逐行倒序打印输入文件(文本文件),但它也倒序打印单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29655194/

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