Search code examples
javastackpalindrome

Java Stack class / Palindrome class


Question: Develop a Stack class (NEEDS TO HAVE (at least) push, pop, and isEmpty methods) (The ONLY data structure you could use/have in your Stack class SHOULD be a CHAR ARRAY)

Second, develop a second Java class named Palindrome that in its main method, receives a string as a command-line argument, and then uses a Stack object to check whether the given string is a palindrome or not.

The Palindrome class would be the ONLY one with the main() method which receives a command-line argument (JUST ONE STRING WITH NO WHITESPACES) and checks whether it's a palindrome or not. It does so by creating an object of class Stack and calling its methods in some parts of your algorithm.

Answer:

public class Stack {

    private int position, capacity;
    private char[] stack;

    public Stack(int n) {
        capacity = n;
        position = -1;
        stack = new char[capacity];
    }

    public void push(char obj) {
        // stack is not full
        position++;
        stack[position] = obj;
    }

    public char pop() {
        // stack is not empty
        char temp = stack[position];
        position--;
        return temp;
    }

    public boolean isEmpty() {
        return position == -1;
    }

    public char peek() {
        return stack[position];
    }

    public boolean isFull() {
        return position == capacity - 1;
    }

}


public class Palindrome {

    public boolean same(char ch1, char ch2) {
        return (ch1 == ch2) ? true : false;
    }

    public boolean palindrom(String s) {
        int len = s.length();
        char token = 0;
        Stack stack = new Stack(len);

        for (int i = 0; i < len; i++) {
            token = s.charAt(i);
            if (token != ' ')
                stack.push(new Character(token));

        }

        for (int j = 0; j < len; j++) {
            token = s.charAt(j);
            if (token != ' ')
                if (!same((Character) (stack.pop()), s.charAt(j)))
                    return false;
        }

        return (stack.isEmpty()) ? true : false;
    }

    public String reverse(String original) {
        String reverse = "";
        int length = original.length();

        for (int i = length - 1; i >= 0; i--)
            reverse = reverse + original.charAt(i);

        return reverse;
    }

    public static void main(String[] a) {
        Palindrome s = new Palindrome();        
        System.out.println( s.palindrom(a[0]) ? "Palindrome" : "Not Palindrome");               
    }
}

Error: Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0 at Palindrome.main(Palindrome.java:41)


Solution

  • System.out.println( s.palindrom(a[0]) ? "Palindrome" : "Not Palindrome");
    

    You probably are not running this program from the command line hence the array a is empty.

    How to run Java program from the command line with arguments