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.
答案 0 :(得分:1)
从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));
}
答案 1 :(得分:0)
请尝试以下代码:
public class BufferReader2 {
public static void main(String[] args) {
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader("README.txt"));
String lines = br.readLine();
ArrayList<String> buffer = new ArrayList<String>();
while (lines != null) {
if(lines != null)
{
buffer.add(lines);
buffer.add("\n");
}
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();
}
}
}
}