java - 递归回文,Java

标签 java

我使用递归来查找字符串是否是回文,同时忽略空格和非字母字符。然而,每个空格都会导致字符串被分割并单独测试。这是我的代码。

public class RecursivePalindrome
{
RecursivePalindrome()
{
}
public boolean checkPalindrome(String y)
{
    String s = y;
    String removed = s.replaceAll("\\W", "");
    removed = removed.toLowerCase();
    return isPalindrome(removed);

}

public boolean isPalindrome(String y)
{
    if ( y.length() < 2 )
      return true;
    char firstChar = y.charAt(0);
    char lastChar = y.charAt(y.length() - 1);

    if(firstChar != lastChar)
      return false;
    else
      return checkPalindrome(y.substring(1, y.length()-1));
}

}

这是测试器类。

import java.util.Scanner;

public class RecursivePalindromeTester
{
public static void main(String [] args)
{
    Scanner in = new Scanner(System.in);
    RecursivePalindrome aMethod = new RecursivePalindrome();
    int z = 0;
    while (z < 1)
    {
        System.out.println("Please enter a word or phrase.(Entering q will stop the program)");
        String n = in.next();
        if(n.equalsIgnoreCase("Q"))
        {
        System.out.println("End of Program");
        z++;
       }
       else{
        if (aMethod.checkPalindrome(n))
        {
          System.out.println(n + " is a palindrome");

        }
        else
        {
            System.out.println(n + " is not a palindrome");
        }}
    }
}

}

最佳答案

Scanner#next() ,根据 javadoc,从此扫描仪查找并返回下一个完整标记,即一个单词(在 空格 处中断)。

Scanner#nextLine()相反,使扫描器前进到当前行并返回跳过的输入,这意味着将写入所有行(在您的情况下,直到按下 Enter 为止)。

in.next()更改为in.nextLine()

关于java - 递归回文,Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28026891/

相关文章:

java - 程序运行正常但是显示很多错误

java - 使用 Selenium 从 google 注册页面访问下拉列表

java - jtextfield 默认光标位置

java - 如何将对象从另一个类传递到 PaintComponent 方法中?

java - FontMetrics.stringWidth() 和 FontMetrics.getStringBounds() 有什么区别?

java - 从内存中读取 JAAS 配置文件的任何方法

java - 在 Java 中传递静态方法

java - 将 MySql DateTime 类型转换为更友好的类型

java - 我如何访问对象属性和对象方法?

java - 如何刷新 JScrollPane 上的 JTable