1

I'm trying my hand at creating my own Stack class in Java. I'm not sure where my code is wrong, but if I enter an actual palindrome into my program console it always returns false. Where is my problem happening?

Here is my palindrome client file: (my stack.java class is accessible in the same program folder.)

public static void main(String args[]) {

//declare both stacks
Stack<String> fwd = new Stack<String>();
Stack<String> rev = new Stack<String>();

//instance variables
String st1;
boolean palindrome = true;

Scanner in = new Scanner(System.in);

System.out.println("Enter a String and I will check if it is a palindrome: \n");

st1 = in.nextLine();

// Read the data in forward order into the Stack
for (int i =0; i < st1.length(); i++) {
  fwd.push(Character.toString(st1.charAt(i)));
}
// Read the same data in reverse order into another Stack
for (int j = st1.length()-1; j >= 0; j--) {
  rev.push(Character.toString(st1.charAt(j)));
}
System.out.println("The string you entered was: ");
System.out.println(fwd.display());
System.out.println(rev.display());
System.out.println();
System.out.println("Checking to see if " + st1 + " is a palindrome.");
System.out.println("/**********************************************");

//check fwd and rev against each other
while (!fwd.isEmpty() && !rev.isEmpty()) {  // make sure stack in not empty
  for (int i = 0; i < st1.length(); i++) {  // go through each element in the stack

     if (fwd.pop() == rev.pop()) //check if fwd pop and rev pop are the same
        palindrome = true;
     else
        palindrome = false;

  }//end for lop
}// end while loop

System.out.println(palindrome);


}// end main

}// end Palindrome

Here is my Stack.java file:

public class Stack<E> implements StackInterface<E> {

   //variables
   private ArrayList<E> data;
   private E element;


   //constructor
   public Stack() {

      data = new ArrayList<E>();
   }


   //stack methods
   public void push(E element) { //push new element into the stack

      data.add(element);
   }

   public E pop() { //pop the element from the top

      if (data.isEmpty()) //if stack is empty, throw exception
         throw new EmptyStackException("The stack is empty.");
      else //else, remove and return the element that is on top of the stack
         return data.remove(data.size()-1); 
   }

   public E peek() { //peek at the element on top of the stack without removing it

      if (data.isEmpty()) //if stack is empty, throw exception
         throw new EmptyStackException("The stack is empty.");
      else //else, return the element that is on top of the class
         return data.get(data.size()-1);   
   }

   public String display() { //display the elements in the stack in the form of a String

      if (data.isEmpty()) //if stack is empty, throw exception
         throw new EmptyStackException("The stack is empty");
      else //else, return elements as a String
         return data.toString();
   }

   public boolean isEmpty() { //check to see if the stack is empty

      if (data.size() == 0)
         return true;
      else
         return false;

   }

   public int size() { //retrurn the number of elements in the stack

      return data.size();

   }

}// end Stack class
Maggie S.
  • 1,076
  • 4
  • 20
  • 30
  • possible duplicate of [How do I compare strings in Java?](http://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java) – chrylis -cautiouslyoptimistic- Oct 22 '13 at 08:11
  • 4
    That moment when you think "today there will be no `==` vs `equals` questions!". – Maroun Oct 22 '13 at 08:12
  • 1
    This is not the solution, but if you add to (!fwd.isEmpty() && !rev.isEmpty()) && palindrome , you save a little bit of runtime. Also after palindrome = false; you can call break, because you already know its no palindrom. – Akkusativobjekt Oct 22 '13 at 08:15
  • @Maroun Still familiarizing myself with the java language. Will not make that silly mistake again, now that I understand the difference! – Maggie S. Oct 22 '13 at 08:15
  • 1
    @MagdaleneB. That's OK :) Everyone do mistakes. – Maroun Oct 22 '13 at 08:17

1 Answers1

5

if (fwd.pop() == rev.pop()) should be if (fwd.pop().equals(rev.pop())) since you're comparing content of two strings.

You should also break your while loop if you detect that it's not a palindrome, otherwise "test" would return true.

if (fwd.pop().equals(rev.pop())) //check if fwd pop and rev pop are the same
                palindrome = true;
             else {
                palindrome = false;
                break;
                 }
}

Edit :

As said in commment the for loop inside the while is actually useless.

Another option would be to create two stacks of Characters and now you can use == to compare them :

Stack<Character> fwd = new Stack<>();
Stack<Character> rev = new Stack<>();

/**/
for (int i =0; i < st1.length(); i++) {
    fwd.push(st1.charAt(i));
}
for (int j = st1.length()-1; j >= 0; j--) {
    rev.push(st1.charAt(j));
}
while (!fwd.isEmpty() && !rev.isEmpty()) {  // make sure stack in not empty
        if (fwd.pop()==rev.pop()) //check if fwd pop and rev pop are the same
           palindrome = true;
        else {
           palindrome = false;
           break; //here break the while loop it's not a palindrom
        }
}// end while loop
Alexis C.
  • 91,686
  • 21
  • 171
  • 177
  • 1
    just to add information, the for loop inside the while is not needed. – RamonBoza Oct 22 '13 at 08:13
  • Thank you that worked! Still familiarizing myself with java in the form of fun little test projects like these. :) – Maggie S. Oct 22 '13 at 08:14
  • @RamonBoza Thank you, I see what you mean and I took it out now. – Maggie S. Oct 22 '13 at 08:20
  • Aha. I see. I tried making a char stack initially but when I got a compile error for making it like this: 'code'Stack fwd = new Stack<>(); I didn't try any further. Now I know how to define a Character Stack, thank you! – Maggie S. Oct 22 '13 at 08:23
  • @MagdaleneB. Notify the break statement. It's very important, otherwise words like "test" would say that is a palindrome. – Alexis C. Oct 22 '13 at 08:24
  • @ZouZou What do you mean by notify? What is that? – Maggie S. Oct 22 '13 at 08:26
  • @MagdaleneB. Pay attention to the `break;` instruction. It actually makes your programm correct. Check my edit =) – Alexis C. Oct 22 '13 at 08:27
  • I see now, for the Character Stack version. So is the break statement still useful/necessary if I were keep it as a String Stack? Probably not since it's not going through each character one by one right? – Maggie S. Oct 22 '13 at 08:29
  • 1
    @MagdaleneB. You can keep your String stack too it's correct. But the main idea of checking a word to be a palindrom is to check character by character. Instead of put the character in a String object you could directly but the character itself in the stack, but your version is ok too =) – Alexis C. Oct 22 '13 at 08:31