Shailab Singh Shailab Singh - 3 months ago 10
Java Question

stack comparision in java

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

if(s.lastElement().equals(str_arry[i])){

s.push(str_arry[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
java.util.Vector.lastElement(Vector.java:503)


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

Answer

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(...) {
    s.push(...);
  } else {
    s.pop();
  }
}
Comments