-1

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

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

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

3 回答 3

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");
        }
    }
}
于 2013-10-05T07:19:45.733 回答
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());
        }
    }
}
于 2013-10-05T07:13:43.550 回答
0
private static boolean isPalindrome(String str) {
    if (str == null)
        return false;
    StringBuilder strBuilder = new StringBuilder(str);
    strBuilder.reverse();
    return strBuilder.toString().equals(str);
}

你可能应该这样做。

于 2013-10-05T07:22:55.877 回答