堆栈为什么不推?

时间:2014-10-17 21:36:24

标签: java data-structures

 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 个答案:

答案 0 :(得分:2)

确实如此。标记生成器需要空格来分隔您的输入。所以像:

1 + 2

会将+推送到堆栈。注意空格!

答案 1 :(得分: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。

我希望这对你来说很明显。