Palindromes are character sequences that read the same forward or backword (e.g.
ID: 3679914 • Letter: P
Question
Palindromes are character sequences that read the same forward or backword (e.g. the strings "mom" or "123 454 321"). You will write a program that uses a recursive function to determine whether a string is a character-unit palindrome.
Your program will take arguments from the command-line, including one or more input strings to be evaluated with your recursive palindrome-checking function. An optional command-line flag (-c), if included in the command line, will tell your program to be case-sensitive for all input strings. The default condition (i.e. if the flag is NOT included) is to ignore case-sensitivity. So, for example, "Mom" should evalate as a palindrome if the -c flag is not included in the command-line, but should evaluate as NOT a palindrome if -c is included.
Important note: Spaces normally separate command line arguments (in this case, the input strings), but a string with spaces can be passed to a program at the command line by putting it in double quotes (e.g. "this will be read by my program as a single string"). The quote characters are not included in the string that gets parsed.
Requirements
Assume that if the case-sensitivity flag (-c) is present, it is always the first parameter passed at the command line.
Allow both uppercase and lowercase versions of the flag (i.e. -c and -C should do the same thing).
Your program should not take any user input (i.e. "cin" should not be anywhere in your code).
You must have the following functions:printUsageInfo - Print program usage information in case no input strings were found at command line.
Parameter(s): a string (passed by constant reference) representing the name of the executable from the command line.
Return: void.
isPalindrome - This function determines whether a string is a character-unit palindrome.
Parameter(s): an input string (passed by constant reference), and a boolean flag that says whether to consider case-sensitivity.
Return: bool.
Explanation / Answer
public class PalindromeTest {
public static void main(String args[]) {
System.out.println("Is aaa palindrom?: " + isPalindromString("aaa"));
System.out.println("Is abc palindrom?: " + isPalindromString("abc"));
System.out.println("Is bbbb palindrom?: " + isPalindromString("bbbb"));
System.out.println("Is defg palindrom?: " + isPalindromString("defg"));
}
public static boolean isPalindromString(String text){
String reverse = reverse(text);
if(text.equals(reverse)){
return true;
}
return false;
}
public static String reverse(String input){
if(input == null || input.isEmpty())
{
return input;
}
return input.charAt(input.length()- 1) + reverse(input.substring(0, input.length() - 1));
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.