Reputation: 21
It won't output a false statement. Not sure why it won't output the correct answer.
When testing, make sure your algorithm works in the following cases:
When given a word that is a palindrome, the algorithm returns "true" When given a word that is not a palindrome, the algorithm returns "false" When given a word that is an empty String, the algorithm does not crash.
public class Palindrome {
public static void main(String[] args) {
String input = "";// Set to test value
char[] phrase = input.toCharArray();
System.out.println(isPalindrome(phrase));
}
public static boolean isPalindrome(char[] input) {
if (input == null)
return false;
int length = input.length;
int c = 0;
while(c <= length/2) {
if(input[c] != input[length - 1 - c])
return false;
c++;
}
return true;
}
}
Upvotes: 1
Views: 689
Reputation: 1454
You can do it the easy way:
public static void main(String args[]) {
System.out.println(isPalindrome("redivider"));
System.out.println(isPalindrome("normal"));
}
public static boolean isPalindrome(String check) {
return new StringBuilder(check).reverse().toString().equalsIgnoreCase(check);
}
or just add "|| input.length == 0"
public static boolean isPalindrome(char[] input) {
if (input == null || input.length == 0) return false;
int length = input.length;
int c = 0;
while (c <= length / 2) {
if (input[c] != input[length - 1 - c]) return false;
c++;
}
return true;
}
Upvotes: 5