# can't see where it went wrong..

• 01-31-2011, 01:14 AM
Yakg
can't see where it went wrong..
Hi, I'm writing a method that checks a palindrome in a stack.
At the moment it returns true even when the values are not equal.
I would appreciate some help, as I didn't locate the problem.

Code:

```public static boolean PalindromeWithStack (Stack s, int numOfElements){ int counter = 0,first,second; Stack s2=new Stack (); if (numOfElements ==0) return true; if (numOfElements ==1) return false; while (counter<numOfElements/2){ s2.push(s.pop()); counter++; } //devide the stacks evenly. if (numOfElements %2 != 0) //if odd number of elements s.pop(); while (counter > 0){ first = s.pop(); second = s2.pop(); if (first!=second){        //after condition return false;  //ends here } counter--;      } return true;     }     }```
Thank you.
• 01-31-2011, 02:48 AM
Junky
Quote:

Originally Posted by Yakg
At the moment it returns true even when the values are not equal.

Really? I got false when it is not a palindrome. What data are you testing your code with?

BTW your code is a bit messy. A better way is: if the current value is equal to the top element on the stack > pop else push. When you are done if the stack is empty then it was a palindrome else it wasn't. Mind you there are 2 special conditions: the first value and the middle value in an odd number of values.
• 01-31-2011, 10:52 AM
Yakg
I'm trying to
put ints in the palindrome, in this case 3 and 1.
As for the parameters it takes the stack with the two items and the number 2 as the second parameter.

I can't use other methods besides: push and pop
• 01-31-2011, 11:25 AM
Yakg
Yeah something doesn't make sense..
In the tester I'm inserting these lines:

Stack s1 = new Stack();
s1.push(1);
s1.push(3);

and then pass it to the method as: (s1,2). The first is the stack and the second is the number of elements..
• 01-31-2011, 12:30 PM
JosAH
Quote:

Originally Posted by Yakg
In the tester I'm inserting these lines:

Stack s1 = new Stack();
s1.push(1);
s1.push(3);

and then pass it to the method as: (s1,2). The first is the stack and the second is the number of elements..

Did you try to use Stack<Integer> instead of just a 'raw' Stack class? As your code is now it doesn't even compile.

kind regards,

Jos
• 01-31-2011, 01:19 PM
Yakg
we are very restricted
this is sounds weird, this is the tester class I've been given so I can't change it.
The only thing is changeable is the palindrome class.
It is compiling well when I try it, just something with the condition maybe is wrong.

We are not allowed to use any other ways to solve it..

thanks for helping me getting through this, hopefully one day I will be able to help in this topic as well.