Chapter 16. PC #5. Palindrome Detector (page 1073) A palindrome is any word, phr
ID: 3844472 • Letter: C
Question
Chapter 16. PC #5. Palindrome Detector (page 1073)
A palindrome is any word, phrase, or sentence that reads the same forward and backward. Here are some well-known palindromes:
Able was I, ere I saw Elba
A man, a plan, a canal, Panama
Desserts, I stressed
Kayak
Write a (JAVA) boolean method that uses recursion to determine whether a String argument is a palindrome. The method should return true if the argument reads the same forward and backward. Demonstrate the method in a program.
The program should ask the user to enter a string, which is checked for palindrome property. The program displays whether the given input is a palindrome or not, then prompts the user to enter another string. If the user enters QUIT (case insensitive, then exit the program).
View required output
Test Case 1
Standard InputdadENTER quitENTER
Explanation / Answer
Below is your program: -
Palindrome.java
import java.util.Scanner;
class Palindrome {
public static boolean isPal(String s) {
// if length is 0 or 1 then String is palindrome
if (s.length() == 0 || s.length() == 1)
return true;
// else check for each character.
if (s.charAt(0) == s.charAt(s.length() - 1))
return isPal(s.substring(1, s.length() - 1));
return false;
}
public static void main(String[] args) {
// For capturing user input
Scanner scanner = new Scanner(System.in);
String string = "";
while (!string.equalsIgnoreCase("Quit")) {
System.out.print("Please enter a string to test for palindrome or type QUIT to exit: ");
string = scanner.nextLine();
if (!string.equalsIgnoreCase("Quit")) {
if (isPal(string))
System.out.println("The input is a palindrome.");
else
System.out.println("The input is not a palindrome.");
}
}
}
}
Sample Run:-
Please enter a string to test for palindrome or type QUIT to exit:
dad
The input is a palindrome.
Please enter a string to test for palindrome or type QUIT to exit:
sas
The input is a palindrome.
Please enter a string to test for palindrome or type QUIT to exit:
sss
The input is a palindrome.
Please enter a string to test for palindrome or type QUIT to exit:
sda
The input is not a palindrome.
Please enter a string to test for palindrome or type QUIT to exit:
123
The input is not a palindrome.
Please enter a string to test for palindrome or type QUIT to exit:
121
The input is a palindrome.
Please enter a string to test for palindrome or type QUIT to exit:
quit
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.