Hello i need help with the popping of stacks.

i want to pop them all once i go into the Clear() method, but im having problems with the codings. here's my code:

import java.util.Stack;
class InfixPost
{
static Stack inputStack;
static String output = "";


public String infixToPostfix(String input) {


inputStack = new Stack();

for (int i = 0; i < input.length(); i++) {
char current = input.charAt(i);
if (current == '+' || current == '-') {
isOperator(current, 1);
} else if (current == '*' || current == '/') {
isOperator(current, 2);
} else {
output += current;
}
}
while(!inputStack.isEmpty()){
char top = (Character) inputStack.pop();
output += top;
}
return output;
}

public static void isOperator(char c, int prec) {
while (!inputStack.isEmpty()) {
char top = (Character) inputStack.pop();
int topPrec = 0;
if (top == '+' || top == '-') {
topPrec = 1;
} else {
topPrec = 2;
}

if (topPrec >= prec) {
output += top;
}else{
inputStack.push(top);
break;
}

}
inputStack.push(c);
}


public void Clear(){

while(!inputStack.isEmpty()){
inputStack.pop();
}

}


}

how can i pop all of the stacks contents? im having problems with my Clear() method.
any advices will be gladly accepted. thanks in advance.

Edited 5 Years Ago by intes77: n/a

Uhm, with clear() ? See the API docs, Stack does have a clear method.

Edited 5 Years Ago by masijade: typos

Your method isn't bad, popping them off one at a time. An easier, more efficient, and less obvious method is to re-initialize the stack:

public void Clear(){
	inputStack = new Stack<Character>();
}

Another solution is using the inherited method:

public void Clear(){
	inputStack.clear();
}

At which point you'll probably just want to call that method from your code and not define your own method.

Note: you'll want to initialize your stack as a data type. From your code, you'll want to do:

static Stack<Character> inputStack;

public String infixToPostfix(String input) {

inputStack = new Stack<Character>();

Edited 5 Years Ago by ztini: n/a

An easier, more efficient, and less obvious method is to re-initialize the stack:

public void Clear(){
	inputStack = new Stack<Character>();
}

That always sounds like a good idea, however, if this class instance is being used in multple threads, it could easily cause some very unpredictable behaviour. Just as a note of warning.

Edit: And it seems as though some people don't like to be reminded that RTFM is sometimes a good idea.

Edited 5 Years Ago by masijade: n/a

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