2013-10-08 5 views
0

내가 뭘 하려는지는 파일을 읽은 후 StringBuilder을 사용하여 문자열 단어의 줄 안에있는 파일의 순서를 뒤집습니다. while 루프에서 작업 할 수있게되었지만 메서드에 추가하면 원본 파일 텍스트가 출력됩니다.자바 메서드 실행 취소 알고리즘

다음은 작동하는 코드입니다. 여기에 인쇄

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

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

이 작동하지 않습니다 코드입니다;

// 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, " "); 
}