这段代码有什么问题(回文检查)

时间:2015-06-06 12:49:13

标签: java

我想写一个回文检查代码,但如果我输入“女士”它仍然告诉我它不是回文请帮助。告诉我什么导致它

import java.util.Scanner;

public class parlindrome
{
    String original, reverse = "";

    public void checkpalindrome(){

        Scanner h = new Scanner(System.in);
        System.out.println("enter a word : ");

        original = h.nextLine();

        int length = original.length();

        for(int i = length-1; i >= 0; i--)
        {
            {
                reverse = reverse + original.charAt(i);
                if(original.equals(reverse))
                {
                    System.out.println("entered word is a palindrom ");
                }
                else
                {
                    System.out.println("entered word is not a palindrome ");
                    break;
                }
            }
        }
    }

    public static void main(String[]args)
    {
        parlindrome k=new parlindrome();
        k.checkpalindrome();
    }
}

4 个答案:

答案 0 :(得分:1)

你应该在检查它是否是回文之前完成反转String的循环:

for(int i=length-1;i>=0;i--) {
    reverse=reverse+original.charAt(i);
}
if(original.equals(reverse)) {
    System.out.println("entered word is a palindrom ");
}

此外,如果您希望此方法多次使用,则应将reverse作为局部变量并将其初始化为方法内的空字符串。

答案 1 :(得分:0)

你可以使用Java的反向更有效地完成它。

public void checkpalindrome(){
    Scanner h = new Scanner(System.in);
    System.out.println("Enter a word: ");
    String original = h.nextLine();

    if(original.equals(new StringBuilder(original).reverse().toString()))
        System.out.println("Entered word is a palindrom");
    else
        System.out.println("Entered word is not a palindrom");
}

答案 2 :(得分:0)

只需从for循环中删除验证部分即可。您的代码应如下所示:

for (int i = length - 1; i >= 0; i--)
    reverse += original.charAt(i);

if (original.equals(reverse))
    System.out.println("entered word is a palindrom ");
else
    System.out.println("entered word is not a palindrome ");

h.close();

答案 3 :(得分:0)

试试这个:

import java.util.Scanner;

public class parlindrome {

    public boolean checkpalindrome(String original) {
        String reverse = "";

        int length = original.length();

        for (int i = length - 1; i >= 0; i--) {
            reverse += original.charAt(i);
        }
        if (reverse.equals(original)) {
            System.out.println("entered word is a palindrom ");

            return true;
        }
        System.out.println("entered word is not a palindrom ");

        return false;

    }

    public static void main(String[] args) {
        Scanner h = new Scanner(System.in);
        System.out.println("enter a word : ");

        String original = h.nextLine();

        parlindrome k = new parlindrome();
        k.checkpalindrome(original);

    }
}