简单的回文问题

时间:2013-10-05 07:11:28

标签: java

我是一名尝试学习编程的业余爱好者。

我正在尝试做回文。但是,我在代码中出错了。

public class Palindrome {

    public static void main(String args[])
    {
    String pal = "abc";

    public static void check(String pal)
    {
        if(pal==null)
        {
            System.out.println("Null Value..Exit");
        }
        else
        {
            StringBuilder str= new StringBuilder(pal);
            str.reverse();
            System.out.println(str.reverse());
        }
    }
    }

}

我哪里错了?对不起,我对编程很新。只是想学习!

4 个答案:

答案 0 :(得分:3)

您需要在代码中进行以下更改。

public static void main(String args[]) {
    String pal = "abc";
    check(pal); // Nested methods are not allowed, thus calling the check
                // method, which is now placed outside main
}

public static void check(String pal) {
    if (pal == null) {
        System.out.println("Null Value..Exit");
    } else {
        StringBuilder str = new StringBuilder(pal);

        // I think I confused you by doing the below.
        // str = str.reverse(); // commenting this

        str.reverse(); // adding this 
        // str.reverse(); reverse will affect the str object. I just assigned it back to make it easier for you
        // That's why if you add a SOP with str.reverse, it'll reverse the string again, which will give the original string back
        // Original string will always be equal to itself. that's why your if will always be true
        // give a SOP with str.toString, not reverse.

        // str.toString is used because str is a StringBuilder object and not a String object.
        if (pal.equals(str.toString())) { // if the string and its reverse are equal, then its a palindrome
            System.out.println("Palindrome");
        } else {
            System.out.println("Not a Palindrome");
        }
    }
}

答案 1 :(得分:2)

你不能在另一个方法中写一个方法。

public class Palindrome {

    public static void main(String args[])
    {
    String pal = "abc";
check(pal);

    }
    public static void check(String pal)
    {
        if(pal==null)
        {
            System.out.println("Null Value..Exit");
        }
        else
        {
            StringBuilder str= new StringBuilder(pal);
            str.reverse();
            System.out.println(str.reverse());
        }
    }
}

答案 2 :(得分:0)

public static boolean checkPalindrome(String str) {
    return str.equalsIgnoreCase(new StringBuilder(str).reverse());
}

答案 3 :(得分:0)

private static boolean isPalindrome(String str) {
    if (str == null)
        return false;
    StringBuilder strBuilder = new StringBuilder(str);
    strBuilder.reverse();
    return strBuilder.toString().equals(str);
}

你应该这样做。