Hello All,

I am using a stack to create a sort of calculator.

My input string will be "5 6 add"

I have to push 5, push 6, and when I get read "add" pop 5 and 6 and and push the answer.

The question is after the string is broken up by the whitespaces, how do I compare each individual part to the string "add" so when it is equal to "add" it will pop the 5 and 6 and I can continue on with my next step?

For example:

is "5" equal to "add" - no, push onto stack
is "6" equal to "add" - no, push onto stack
is "add" equal to "add" - yes, pop 6, pop 5 and (continue)

Any assistance will be appreciated.

Thanks,

The question I have is when I push 5 and push 6, when I get to "add" how to I use it ias a comparison

When you pop, place the value in a string and compare it with the String "add":
for example (not exaclty java code because i don;t remember by heart the right syntax)

String s=stack.pop();

if (s.equals("add")) {
  int i=Integer.parseInt( stack.pop() );
  int j=Integer.parseInt( stack.pop() );
  int res=i+j;
  stack.push( String.valueOf(res) );
} else if (s.equals("sub")) {
  //do something
} else if (s.equals("mult")) {
  //do something
} else if (s.equals("div")) {
  //do something
} else {
  stack.push(s);//it puts it back because it is (probably) a number
}

This is just a general idea. I don't know what exactly you want to do and how you want to push or pop things in the stack

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.