1
votes

I have to compare Boolean values in a array by using the isPalindrom() method. I cant not get my program to accurately return the answer if an array is or is not a palindrome. It just always returns true instead of false when I purpose use a non palindrome answer. Code:

 public Boolean isPalindrome()
 {
    Boolean result = true;
    for(int i=0;i<bits.length;i++)
    {
        Boolean a = bits[i];
        Boolean b = bits[bits.length - i - 1];
        if(a!=b)
            result = false;      
    }
    return result;    
 }
4
For starters, why are you using Boolean?chrylis -cautiouslyoptimistic-
For homework, it evidently makes it easier to compare the array as a palindrome.Lonely Twinky
Fairly soon you'll want to learn the difference between the wrapper types (Boolean) and the primitives (boolean). Unless you're putting it into a collection, there's almost never a reason to use the wrapper for boolean.chrylis -cautiouslyoptimistic-

4 Answers

1
votes

Perhaps using Integer type (if values are all numeric) would work better than boolean for (a) and (b)?

public Boolean isPalindrome()
     {
        Boolean result = true;
        for(int i=0;i<bits.length;i++)
        {
            int a = bits[i];
            int b = bits[bits.length - i - 1];
            if(a!=b)
                return false;      
        }
        return true;    
     }
1
votes

instead of != use below code

if (!(a.Equals(b)))

Hope it works.

1
votes

Try the code below:

public class TestC {

    public static void main(String[] args) {
        Boolean[] bits = { Boolean.FALSE, Boolean.TRUE, Boolean.FALSE,
                Boolean.FALSE };
        Boolean[] bits1 = { Boolean.TRUE, Boolean.TRUE, Boolean.TRUE,
                Boolean.TRUE };
        Boolean[] bits2 = { Boolean.FALSE, Boolean.TRUE, Boolean.FALSE };
        System.out.println(isPalindrome(bits));
        System.out.println(isPalindrome(bits1));
        System.out.println(isPalindrome(bits2));

    }

    public static Boolean isPalindrome(Boolean[] bits) {
        Boolean result = true;
        for (int i = 0; i < bits.length; i++) {
            Boolean a = bits[i];
            Boolean b = bits[bits.length - i - 1];
            if (a != b)
                result = false;
        }
        return result;
    }
}
0
votes

The method looks correct, even though it's not the optimized/efficient one. It should return the correct true/false for the palindrome test. Could you provide the set of inputs you're testing with?