0

我想要做的是读取一个文件并使用StringBuilder来反转文件内部的顺序,即一行字符串。我让它在while循环中工作,但是当我将它添加到一个方法时,它只会打印出原始文件文本。

这是有效的代码;

// File being read....
while ((currentString = s.next()) != null) {
    a.insert(0, currentString);
    a.insert(0," ");
}

打印

line. this reads it hope I file. this read will program This

这是不起作用的代码;

// File being read....
while ((currentString = s.next()) != null) {
    System.out.print(reverse(currentString));
} 

方法

public static StringBuilder reverse(String s){
    StringBuilder a = new StringBuilder();
    a.insert(0, s);
    a.insert(0," ");
}

打印

This program will read this file. I hope it reads this line.

我究竟做错了什么?

4

2 回答 2

2

StringBuilder a每次调用时,您都在创建一个新的reverse()。您需要保留对的引用StringBuilder才能正确地将所有字符串附加到它。

// File being read....
StringBuilder a = new StringBuilder();

while ((currentString = s.next()) != null) {
    reverse(a, currentString);
}

// ...

public static void reverse(StringBuilder a, String currentString) {
    a.insert(0, s);
    a.insert(0," ");
}
于 2013-10-08T21:20:43.140 回答
2

您正在创建一个新的 StringBuilder 并在阅读每个单词时打印它。您需要建立字符串,然后在所有阅读后打印。如果您想在方法中反转但在方法之外读取每个单词,那么您可以将当前 StringBuilder 提供给您的反转方法,例如

StringBuilder total = new StringBuilder();
while ((currentString = s.next()) != null) {
    reverse(total, currentString);
}
System.out.print(currentString);

public static void reverse(StringBuilder total, String s) {
    total.insert(0, s);
    total.insert(0, " ");
}
于 2013-10-08T21:22:26.210 回答