2014-10-17 75 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。

我希望这对你的队友来说足够清楚。