Reputation: 91
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().
Upvotes: 0
Views: 93
Reputation: 140299
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();
}
}
Upvotes: 3