回文是指从后向前读和从前向后读都相同的名称、数字或字符串。
示例:madam、level、mom、noon
这里我们解释如何编写一个 Java 程序,使用递归函数检查字符串是否为回文。

首先,我们必须声明 Palindrome 类。然后我们必须从用户读取一个字符串到变量 str 中。通过使用 if 条件调用函数 isPalindrome(str)。如果它返回 true 值,那么我们将显示该字符串是回文,否则,我们将显示该字符串不是回文。
该函数检查 s.length()=0 或 s.length()=1,如果为 true 则函数返回 true。否则它将检查字符串的第一个字符和最后一个字符是否相等。如果相等,则我们将检查下一个字符与倒数第二个字符,依此类推,直到字符串长度变为 1 或零。如果字符串不是回文,则函数返回 false。
步骤 1:声明带有 public 修饰符的类 Palindrome 。
步骤 2:打开 main() 开始程序,Java 程序执行从 main() 开始
步骤 3:声明字符串变量 str。
步骤 4:从用户读取字符串到变量 str 中。
步骤 5:通过使用 if 条件检查 isPalindrome (str) 是 true 还是 false。如果为 true 则显示字符串是回文。否则显示字符串不是回文。
函数 static boolean isPalindrome(String s)
步骤 1:检查 s.length()==0 或 s.length()==1,然后返回 true。
步骤 2:否则检查字符串的第一个字符和最后一个字符是否相等,如果相等则返回 isPalindrome(s.substring(1, s.length()-1));
步骤 3:返回 false。
import java.util.Scanner;
public class Palindrome {
public static void main(String[] args) {
Scanner sc = new Scanner(System. in );
System.out.println("Enter the String:");
String str = sc.nextLine();
if (isPalindrome(str)) System.out.println(str + " is a palindrome string");
else System.out.println(str + " is not a palindrome string");
}
public static boolean isPalindrome(String s) {
if (s.length() == 0 || s.length() == 1) return true;
if (s.charAt(0) == s.charAt(s.length() - 1))
return isPalindrome(s.substring(1, s.length() - 1));
return false;
}
}
Enter the String: madam madam is a palindrome string