Question

This program is supposed to read the values of the string input and return a result.

However, when I use

System.out.println(Arrays.toString(stack.toArray()));

to check what the stack looks like at the end, or even during the program, I noticed that the pop() method foe the stack doesn't seem to be removing the elements it's returning.

I'm probably doing something horribly wrong, but I haven't been able to figure it out.

I'd really appreciate any insight !

// Test example : (((1+1)+1)+1)

import java.util.*;

public class Task2 
{
public static void main(String[] args) //run Start() method
{
    System.out.print("Enter an expression, or press Enter to quit: ");

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

    Scanner scanner = new Scanner(System.in);

    String n = scanner.nextLine();

    if(!n.isEmpty())
    {
        for(int i = 0 ; i < n.length() ; i++)
        {
            if(!(n.charAt(i) == ')'))
            {
                stack.push(n.charAt(i) + "");
            }
            else
            {
                int two = Integer.parseInt(stack.pop());
                char op = (stack.pop()).charAt(0);
                int one = Integer.parseInt(stack.pop());

                switch(op)
                {
                    case '+':{stack.push((one + two) + "");}
                    case '-':{stack.push((one - two) + "");}
                    case '*':{stack.push((one * two) + "");}
                    case '/':{stack.push((one / two) + "");}
                }
            }
        }
    }
    else
    {
        System.out.print("\ngoodbye");

        System.exit(0);
    }
  }
}

Sorry for the lack of comments, and thanks !

Était-ce utile?

La solution

This is my first solution here, so be gentle :D. The issue was not with pop(), as pop was doing what it was supposed to. You forgot to add break points in your switch statement. It did every operation and added it to the stack giving it the illusion that pop was not working. I will leave the printing part to you. Cheers.

                switch(op)
                {
                case '+':
                    stack.push((one + two) + "");
                    break;
                case '-':
                    stack.push((one - two) + "");
                    break;
                case '*':
                    stack.push((one * two) + "");
                    break;
                case '/':
                    stack.push((one / two) + "");
                    break;
                }
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top