The problem
Write program in java that accepts users input and validates if the input is a palindrome. A palindrome is a word that reads the same forwards as it does backwards. For this exercise we will consider a palindrome a palindrome without punctuation.
Breaking it down
Ask user for word or phrase
// Create a Scanner object for keyboard input.
Scanner keyboard = new Scanner(System.in);
// Get user input
System.out.print("Enter a word or phrase: ");
String userInput = keyboard.nextLine();
Write a method isPalindrome
/**
* Method should return true if a string is identified as a palindrome.
* There are many ways to do a palindrome check, this is just one of them.
* If you are performing checks on very, very long strings you may want to
* consider another algorithm.
*
* @param str
* @return
*/
public static boolean isPalindrome(String str) {
if (str.length() <= 1) {
return true;
} else {
String toCompare = str.replaceAll("\s+","");
StringBuffer buffer = new StringBuffer(toCompare);
String reversedString = buffer.reverse().toString();
if (reversedString.equalsIgnoreCase(toCompare)) {
return true;
} else {
return false;
}
}
}
Check word or phrase, display result
boolean isAPalindrome = isPalindrome(userInput);
if (isAPalindrome) {
System.out.print("The word or phrase is a palindrome");
} else {
System.out.print("Sorry the word or phrase is NOT a palindrome");
}
Output
Enter a word or phrase: Able was I ere I saw Elba
The word or phrase is a palindrome
Unit tests
@Test
public void is_a_palindrome_single_char () {
assertTrue(PalindromeDiscoverer.isPalindrome("A"));
}
@Test
public void is_a_palindrome () {
assertTrue(PalindromeDiscoverer.isPalindrome("bob"));
}
@Test
public void is_a_palindrome_mixed_case () {
assertTrue(PalindromeDiscoverer.isPalindrome("A but tuba"));
}
@Test
public void is_a_palindrome_longer_phrase () {
assertTrue(PalindromeDiscoverer.isPalindrome("Able was I ere I saw Elba"));
}
@Test
public void is_not_a_palindrome () {
assertFalse(PalindromeDiscoverer.isPalindrome("Free beer, I am there..."));
}
Level Up
- Validate user input
- Allow user to enter in more than one check
- A palindrome is often considered true excluding spaces or punctuation, enhance the program to punctuation