Shailab Singh Shailab Singh - 10 months ago 27
Java Question

stack comparision in java

for(int i=1;i<str_arry.length;i++){



else {
if(!s.isEmpty()) s.pop();


i was not able to detect why this one is giving Exception in thread "main"

java.util.NoSuchElementException at

Since the code s.pop() is the cause of that exception but how could this be possible if it's i used s.isEmpty().


It's not s.pop() that's causing the exception: it's s.lastElement(), as indicated by java.util.Vector.lastElement in the stack trace. This means that you have to check for s.isEmpty() before calling s.lastElement() too.

You can't execute any of the loop body if the stack is empty: move the check outside:

for (int i=1;i<str_arry.length;i++) {
  if (s.isEmpty()) break;  // Or some other way to handle it.

  if (s.lastElement().equals(...) {
  } else {