Finding Palindromes in an Array
- by Jack L.
For this assignemnt, I think that I got it right, but when I submit it online, it doesn't list it as correct even though I checked with Eclipse.
The prompt:
Write a method isPalindrome that accepts an array of Strings as its argument and returns true if that array is a palindrome (if it reads the same forwards as backwards) and /false if not. For example, the array {"alpha", "beta", "gamma", "delta", "gamma", "beta", "alpha"} is a palindrome, so passing that array to your method would return true. Arrays with zero or one element are considered to be palindromes.
My code:
public static void main(String[] args) {
String[] input = new String[6]; //{"aay", "bee", "cee", "cee", "bee", "aay"} Should return true
input[0] = "aay";
input[1] = "bee";
input[2] = "cee";
input[3] = "cee";
input[4] = "bee";
input[5] = "aay";
System.out.println(isPalindrome(input));
}
public static boolean isPalindrome(String[] input) {
for (int i=0; i<input.length; i++) { // Checks each element
if (input[i] != input[input.length-1-i]){
return false; // If a single instance of non-symmetry
}
}
return true; // If symmetrical, only one element, or zero elements
}
As an example, {"aay", "bee", "cee", "cee", "bee", "aay"} returns true in Eclipse, but Practice-It! says it returns false. What is going on?