Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 12 of 12

Thread: Im not sure whats wrong with my code

  1. #1
    Junior Member
    Join Date
    Jan 2013
    Posts
    11
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Im not sure whats wrong with my code

    PalindromeChecker.java

     
    /**
     * @author lisit
     *
     * @param <T>
     */
    public class PalindromeChecker<T> {
     
     
        @SuppressWarnings("javadoc")
    	private ArrayStack<T> theStack;
        /**
         * @param input
         */
        @SuppressWarnings({ "unchecked", "rawtypes" })
     
        /**
         * @param input
         */
        public PalindromeChecker(T[] input) {
        	theStack = new ArrayStack(input.length);
    	    	for(int i=0; i < input.length; i++)
    	    	{
    	    		theStack.push(input[i]);
    	    	}
        }
     
        /**
         * @return
         */
        public boolean isPalindrome() {
        	int stacklength = 0;
        	Object[] temp = (Object[]) new Object [50];
    	    	for(int i=0; !theStack.isEmpty(); i++){
    	    		temp[i] = theStack.pop();
    	    		stacklength++;
    	    		System.out.println(stacklength);
    	    	}
          	boolean tof = false;
    	    	for(int j=0; j < stacklength ; j++){
    	    		if((j==0)&&(temp[0] == temp[stacklength-1])){
    	       				tof = true;
    	       		}	
    	      		else if(temp[j] == temp[stacklength-j]){	
    	    			tof = true;
    	    		}
    	    	}
        	return tof;	
        }
     
     
    }

    ArrayStack.java

     
    /**
     * @author lisit
     *
     * @param <T>
     */
    public class ArrayStack<T> implements StackInterface<T> {
     
    	private T[] stack;
    	private int topIndex;
    	private static final int DEFAULT_INITIAL_CAPACITY = 50;
     
    	/**
    	 * 
    	 */
    	public ArrayStack()
    	{
    		this(DEFAULT_INITIAL_CAPACITY);
    	}
     
    	/**
    	 * @param initialCapcity
    	 */
    	public ArrayStack(int initialCapcity)
    	{
    		@SuppressWarnings("unchecked")
    		T[] tempStack = (T[]) new Object[initialCapcity];
    		stack = tempStack;
    		topIndex = -1;
    	}
     
        @Override
        public void push(T newEntry) {
        	topIndex++;
        	stack[topIndex] = newEntry;
     
        }
     
        @Override
        public T pop() {
    	    topIndex--;
    	    return stack[topIndex+1];
        }
     
        @Override
        public T peek() {
        	return stack[topIndex];
        }
     
        @Override
        public boolean isEmpty() {
        	if(stack.length == -1)
        		return true;
        	else
        		return false;
        }
     
        @Override
        public void clear() {
            topIndex = -1;
        }
     
    }

    PalindromeCheckerTest.java
    public class PalindromeCheckerTest {
     
        public static void main(String[] args) {
            int testsPassed = 0;
            int testsAttempted = 0;
     
            PalindromeChecker<Character> pcC1 = new PalindromeChecker<Character>(
                    toCharArray("abcd"));
            if (pcC1.isPalindrome()) {
                testsPassed++;
            }
            testsAttempted++;
     
     
            PalindromeChecker<Character> pcC2 = new PalindromeChecker<Character>(
                    toCharArray("stack"));
            if (!pcC2.isPalindrome()) {
                testsPassed++;
            }
            testsAttempted++;
     
     
            String[] arr1 = { "I", "love", "CS", "love", "I" };
            PalindromeChecker<String> pcS1 = new PalindromeChecker<String>(arr1);
            if (pcS1.isPalindrome()) {
                testsPassed++;
            }
            testsAttempted++;
     
            // Here you will write some more tests
            // ....
            //
     
            // If you do the extra credit, uncomment these tests, and write
            // some of your own.
            // PalindromeChecker<Character> pcExtra1 = new
            // PalindromeChecker<Character>(
            // sentenceToCharArray("A man, a plan, a canal. Panama."));
            // if (pcExtra1.isPalindrome()) {
            // testsPassed++;
            // }
            // testsAttempted++;
            //
            // PalindromeChecker<Character> pcExtra2 = new
            // PalindromeChecker<Character>(
            // sentenceToCharArray("I Palindrome I"));
            // if (!pcExtra2.isPalindrome()) {
            // testsPassed++;
            // }
            // testsAttempted++;
     
            // If you do the extra extra credit, uncomment these tests, and write
            // some of your own.
            /*PalindromeChecker<Integer> pcExtraExtra1 = new PalindromeChecker<Integer>(
                    intToIntArray(1331));
            if (pcExtraExtra1.isPalindrome()) {
                testsPassed++;
            }
            testsAttempted++;
     
            PalindromeChecker<Integer> pcExtraExtra2 = new PalindromeChecker<Integer>(
                    intToIntArray(1337));
            if (!pcExtraExtra2.isPalindrome()) {
                testsPassed++;
            }
            testsAttempted++;*/
     
            System.out.println("Congratulations. You passed " + testsPassed
                    + " of " + testsAttempted + " tests!");
        }
     
        /**
         * @param s
         *            a String to be converted to an array of Character objects
         * @return the array of Characters created
         */
        private static Character[] toCharArray(String s) {
            Character[] array = new Character[s.length()];
            for (int i = 0; i < s.length(); i++) {
                array[i] = new Character(s.charAt(i));
            }
            return array;
        }
     
        // Extra Credit: Write (and document) a utility function that takes in a
        // single string that is a sentence, and returns an array of Characters
        // (only lowercase,
        // no punctuation or whitespace) that a PalindromeChecker<Character> can
        // take as input. This is so you can test that something like "A man, a
        // plan, a canal. Panama." is a palindrome based on the characters, even
        // though it is not if we look at the words.
     
       // private static Character[] sentenceToCharArray(String sentence) {
       //     return null;
       // }
     
        // Extra Extra Credit: Write (and document) a utility function that takes in
        // an Integer and converts it to an array of Integers that a
        // PalindromeChecker<Integer> can take as input. The array of Integers
        // will be the digits in the base-10 representation of the input. So,
        // for example, intToIntArray(12345) will return [1,2,3,4,5]
     
        //private static Integer[] intToIntArray(Integer input) {
        //    return null;
        //}
    }

    and this is my error
    1
    2
    3
    4
    Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1
    	at ArrayStack.pop(ArrayStack.java:42)
    	at PalindromeChecker.isPalindrome(PalindromeChecker.java:35)
    	at PalindromeCheckerTest.main(PalindromeCheckerTest.java:9)


  2. #2
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: Im not sure whats wrong with my code

    Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1
    at ArrayStack.pop(ArrayStack.java:42)
    At line 42 the index to an array had a value of -1.
    The range of values is 0 to the array length-1.

    The code needs to keep the value of the index in range. Look at line 42 and see how it got an index of -1.
    If you don't understand my answer, don't ignore it, ask a question.

  3. #3
    Junior Member
    Join Date
    Jan 2013
    Posts
    11
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Im not sure whats wrong with my code

    im new to java and you just confused me more haha could you explain differently

  4. #4
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: Im not sure whats wrong with my code

    Look at line 42
    Find the array that is being indexed on that line
    Find the index that is used (the index is inside the []s
    See what the value of the index is. Add a println to print it out if you can not see what it's value could be
    How can the value of that index be -1?
    If you don't understand my answer, don't ignore it, ask a question.

  5. #5
    Super Moderator pbrockway2's Avatar
    Join Date
    Jan 2012
    Posts
    987
    Thanks
    6
    Thanked 206 Times in 182 Posts

    Default Re: Im not sure whats wrong with my code

    You read the stack trace from the top down to see, first, where the exception happened and then, as you read down, what was happening at the time.

    An ArrayIndexOutOfBoundsException means that you were accessing an array but using a weird index - in this case -1. It happened at line 42 of ArrayStack.java which (I'm guessing) is this one:

    return stack[topIndex+1];

    So it would appear that topIndex is equal to -2 when the exception occurs. You can test this by printing its value:

    @Override
    public T pop() {
        topIndex--;
        System.out.println("pop() about to return stack element, topIndex=" + topIndex);
        return stack[topIndex+1];
    }

    If it turns out that topIndex has been decremented to -2 that suggests that you were popping a basically empty stack.

    The next line in the stack trace (line 35 of PalindromeChecker.java) is saying that what was going on when you accessed the empty stack was the first for loop of isPalindrome().

    for(int i=0; !theStack.isEmpty(); i++){
        temp[i] = theStack.pop();
        stacklength++;
        System.out.println(stacklength);
    }

    Perhaps you should check and verify that isEmpty() is doing what it should. Since its operation depends critically on the value of stack.length you might want to print that value out as part of isEmpty(). But, again, I think code has to be written that actually checks and verifies that isEmpty() is functioning as you intend it should.

  6. #6
    Junior Member
    Join Date
    Jan 2013
    Posts
    11
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Im not sure whats wrong with my code

    Thank you guys so much! but now im working on fixing my isPalidrome function here is what im at now if anyone wants to look

     
    public boolean isPalindrome() {
        	int stacklength = 0;
        	Object[] temp = (Object[]) new Object [50];
    	    	for(int i=0; !theStack.isEmpty(); i++){
    	    		temp[i] = theStack.pop();
    	    		stacklength++;
     
    	    	}
          	boolean tof = false;
          	System.out.println(stacklength);
    	    	for(int j=0; j < stacklength ; j++){
    	      		if((j==0)){
    	    			if(temp[0] == temp[stacklength-1]){
    	       				tof = true;
    	    			}	
    	    		}
    	      		else if(temp[j] == temp[stacklength-1-j]){	
    	    			tof = true;
    	    		}
    	    	}
        	return tof;	
        }

    and my output is when i enter radar

    5
    r r
    d a
    Congratulations. You passed 1 of 1 tests!

    it says it works but d and a arent equal so i dont know what gives

  7. #7
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: Im not sure whats wrong with my code

    What type of Objects go in temp? You should use the equals() method to compare many objects instead of the == operator.
    If you don't understand my answer, don't ignore it, ask a question.

  8. #8
    Junior Member
    Join Date
    Jan 2013
    Posts
    11
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Im not sure whats wrong with my code

    i tried using

     
     
    else if(temp[j].equals(temp(stacklength-1-j))){

    but its giving me an error for the temp in the .equals

  9. #9
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: Im not sure whats wrong with my code

    its giving me an error
    Please copy the full text of the error message and paste it here.

    Are there two temps? One an array[] and one a method()?
    If you don't understand my answer, don't ignore it, ask a question.

  10. #10
    Junior Member
    Join Date
    Jan 2013
    Posts
    11
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Im not sure whats wrong with my code

    sorry

     
    Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
    	The method temp(int) is undefined for the type PalindromeChecker<T>
     
    	at PalindromeChecker.isPalindrome(PalindromeChecker.java:60)
    	at PalindromeCheckerTest.main(PalindromeCheckerTest.java:9)

  11. #11
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: Im not sure whats wrong with my code

    method temp(int) is undefined
    The compiler can not find a method named temp that takes an int for an argument.

    Are there two temps? One that is an array (uses:[]) and one a method (uses: ( ))?

    Change the ()s to []s on line 60
    If you don't understand my answer, don't ignore it, ask a question.

  12. #12
    Junior Member
    Join Date
    Jan 2013
    Posts
    11
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Im not sure whats wrong with my code

    ahhh yes wow i cant believe i missed that! but its all done now thank you so much for your help

Similar Threads

  1. help me with a code, whats wrong?
    By Heizzer10 in forum What's Wrong With My Code?
    Replies: 1
    Last Post: October 17th, 2012, 10:09 AM
  2. Whats wrong with my code??
    By mozza in forum What's Wrong With My Code?
    Replies: 1
    Last Post: May 14th, 2012, 10:37 AM
  3. whats wrong with my code.
    By jove in forum Object Oriented Programming
    Replies: 3
    Last Post: July 30th, 2011, 11:45 PM
  4. Whats wrong with my code!!
    By nitwit3 in forum What's Wrong With My Code?
    Replies: 2
    Last Post: July 22nd, 2011, 11:45 AM
  5. Whats wrong with my code?
    By mlan in forum What's Wrong With My Code?
    Replies: 3
    Last Post: November 27th, 2010, 01:42 PM

Tags for this Thread