2013-10-08 54 views
0

我想要做的是读取一个文件并使用StringBuilder来颠倒文件内部是一串字符串的顺序。 我知道它在while循环中工作,但是当我将它添加到一个方法时,它只是打印出原始文件的文本。Java方法撤消算法

下面是可用的代码;

// 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. 

我在做什么错?

回答

2

您每次拨打reverse()时都会创建一个新的StringBuilder a。您需要保留对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," "); 
} 
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, " "); 
}