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);

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

                } else if (token.matches("*?")) {
                } else if (token.matches("/?")) {
5 Years
Discussion Span
Last Post by JeffGrigg

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 topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.