Reputation: 571
I am trying to compare two seperate stacks to see if they are the same or not. I have a loop iterate through each object in each stack and compare both objects. What I want to happen is if they are equal, continue the loop and return true. If they are not equal at any given point, break the loop and return false. This is what I have written:
public boolean isPalindrome (Stack a, Stack b) {
Object temp1;
Object temp2;
boolean answer;
for (int i = 0; a.size() > 0; i++) {
temp1 = a.pop();
temp2 = b.pop();
if (temp1 != temp2) {
answer = false;
}
else {
answer = true;
}
}
return answer;
}
What I see happening in this is that I have a boolean, and through each loop that boolean is assigned a value depending on what the objects are, then at the end of the loop, return that boolean in its most recent state. No matter what I initialize the variable to, its like the loop does absolutely nothing to it. Can you not modify or return a boolean in a loop? What would be the better way to go about this instance? I have looked at tons of other posts for similar issues, but most of them seem to be trying something a little different ad I would like to stick as true to my original ideas as possible, I just need to know what I am doing wrong. Any suggestions would help greatly. Thanks!
Upvotes: 0
Views: 109
Reputation: 11244
The basic idea that you can return false
(which breaks method execution) once you find stacks are not equal. Otherwise return true
:
public boolean isPalindrome (Stack a, Stack b) {
if (a.size() != b.size()) {
return false;
}
while (a.size() > 0) {
if (!a.pop().equals(b.pop())) {
return false;
}
}
return true;
}
Upvotes: 1
Reputation: 9090
My suggestion:
public boolean isPalindrome (Stack a, Stack b) {
if (a.size() != b.size()) return false;
while (a.size() > 0) {
if (a.pop() != b.pop()) {
return false;
}
}
return true;
}
Upvotes: 1
Reputation: 3729
You need to place a return
statement when you find a false item -- else, you're simply returning the boolean found in the last iteration of your loop.
public boolean isPalindrome (Stack a, Stack b) {
Object temp1;
Object temp2;
boolean answer;
for (int i = 0; a.size() > 0; i++) {
temp1 = a.pop();
temp2 = b.pop();
if (temp1 != temp2) {
answer = false;
return answer;
}
else {
answer = true;
}
}
return answer;
}
Upvotes: 1
Reputation: 3257
public boolean isPalindrome (Stack a, Stack b) {
Object temp1;
Object temp2;
boolean answer = true;
for (int i = 0; a.size() > 0; i++) {
temp1 = a.pop();
temp2 = b.pop();
if (temp1 != temp2) {
answer = false;
break;
}
}
return answer;
}
Upvotes: 1
Reputation: 944
You should put a break statement in just after answer is set to false. Without this, you are returning false only if the last items are not equal.
Quick note: I would also add a check for the case that the two stacks are not the same size.
Upvotes: 0