2014-10-17 79 views
0
public class Rpie { 
    public static void main(String[] args) { 
     Scanner input = new Scanner(System.in); 
     String rpie = input.nextLine(); 
     StringTokenizer string = new StringTokenizer(rpie); 

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

     while (string.hasMoreTokens()) { 
      String tkn = string.nextToken(); 
      if (tkn.equals("+") || tkn.equals("-") || tkn.equals("*") 
        || tkn.equals("/")) { 
       stack.push(tkn); 

      } 

     } 
     System.out.println(stack); 

    } 
} 

爲什麼堆棧在讀取+, - ,*或/?時不會推送字符串?爲什麼堆棧沒有推動?

它輸出一個空的堆棧。

+2

向我們顯示您的輸入。 – MarsAtomic 2014-10-17 21:39:48

+0

我建議你在你的循環打印信息開始 - 例如 '如果(...){'' 的System.out.println( 「獲得」 + TKN);' 'stack.push(TKN );' 或類似的東西。通過這種方式,您可以更好地瞭解可能會導致問題的原因......如果您需要更多幫助,請發佈結果 – Hagai 2014-10-17 21:40:49

回答

2

它的確如此。標記器需要空格來分隔輸入。所以喜歡的東西:

1 + 2

將推動+堆棧。注意空格!

1

檢查文檔:

public StringTokenizer(String str) 

Constructs a string tokenizer for the specified string. 
The tokenizer uses the default delimiter set, which is " \t\n\r\f": 
the space character, 
the tab character, 
the newline character, 
the carriage-return character, 
and the form-feed character. 

Delimiter characters themselves will not be treated as tokens. 

因此,這意味着,如果你不指定一個分隔符,你需要這些默認的分隔符,否則之一,如果你給字符串中竟然沒有他們中的一個你的程序,比如說你輸入「1 + 2-3 * 4/5」,那麼只有一個令牌,它是'1 + 2-3 * 4/5',但是如果你讓我們說空格字符就像這個「1 + 2 - 3 * 4/5」,那麼你的程序將打印「[+, - ,*,/]」,因爲那些是你允許進入堆棧的唯一因爲if。

我希望這對你的隊友來說足夠清楚。