2014-02-13 113 views
0

我應該使用以字符串作爲參數並返回字符串的幫助器方法來顛倒句子中的單個單詞。該堆棧應該是輔助方法。所以我的程序工作,它正確地反轉了單詞。但反向沒有實際返回,我認爲它只是打印堆棧。任何人都可以幫助我返回並打印字符串變量'reverse'。Java從棧中返回字符串

import java.util.Scanner; 
import java.util.Stack; 

public class ReverseStack 
{ 
    public static void main(String[] args) 
    { 
     String sentence; 

     System.out.print("Enter a sentence: "); 
     Scanner scan = new Scanner(System.in); 

     sentence = scan.nextLine(); 

     System.out.println("Reversed:" + PrintStack(sentence)); 
    } 

    private static String PrintStack(String sentence) 
    { 
     String reverse = ""; 
     String next = ""; 

     Stack<String> stack= new Stack<String>(); 

     String words[] = sentence.split(" "); 

     for(int j = 1; j<words.length +1; j++) 
     { 
      String newWord = words[words.length - j]; // Single word 

      for(int i = 0; i < newWord.length(); i++) 
      { 
        next = newWord.substring(i,i+1); 
        stack.push(next); 
      } 
      stack.push(" "); 
     } 
     while(!stack.isEmpty()) 
     { 
      reverse += stack.pop(); 
     } 
     return reverse; 
    } 
} 
+0

字符串是不可變的。 – Maroun

+0

您的程序正在返回並打印字符串變量'reverse'。 –

+0

@Simon但它不打印出堆棧而不是反向字符串?它打印PrintStack(句子)不是反轉 – user3071909

回答

1

您正在倒轉兩次,並以相同的順序結束。您的堆棧會給出相反的順序,但是您將以相反的順序添加這些單詞,所以順序不變。

如果你使用了一個調試器,它應該是顯而易見的問題是什麼。

BTW您可以使代碼更短。

private static String printStack(String sentence) { 
    Stack<String> stack= new Stack<String>(); 
    for(String word: sentence.split(" ") 
     stack.push(word); 
    String line = stack.pop(); 
    while(!stack.isEmpty()) 
     line += " " + stack.pop(); 
    return line; 
}