Start New Discussion within our Software Development Community

hi,
I'm trying to write simple culaction programe using stack .. the GUI is simple one textField and one textBox for the outbut and one button
this is what I wrote in the button I tried the first operation "-" and it work but I got stuck doing the other operations

  String input = txtInput.getText();
        Stack stack = new Stack();
        int temp = 0;


        Scanner sc = new Scanner(input);
        while (sc.hasNext()) {

            String token = sc.next();

            if (token.matches("-?\\d*")) {
                if (token.matches("\\d*")) {
                    int num = Integer.parseInt(token);
                    stack.push(num);

                } else if (token.matches("-?")) {
                    int num1 = (int) stack.pop();
                    int num2 = (int) stack.pop();
                    int total = num2 - num1;
                    temp = total; 
                    stack.push(total);
                    txtOutput.append(stack.peek() + "\n");
                } else if (token.matches("+?")) {

                } else if (token.matches("*?")) {
                } else if (token.matches("/?")) {
                }
            }
        }

I'm going to guess that the other operations are not working because it keeps doing the minus operation, even when you put in '+' or '*' or '/'.

Did you know that the '?' in a regular expression means that it's OK for the character right before it to be there or not?

So } else if (token.matches("-?")) { will match "-", but it will also match the empty string ("").

You probably don't want the question mark characters ("?") in any of the last four if statements.

This article has been dead for over six months. Start a new discussion instead.