你需要在你的代碼下面的變化。
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");
}
}
}
您不能在Java中嵌套函數。 –
首先,在你編寫任何代碼之前,停下來想一想程序應該做什麼。它應該採取哪些步驟?結果應該是什麼?它應該如何構建?在開始編寫代碼之前有一個計劃。 – Jesper
當您發生錯誤時,首先要做的是讀取它,因爲該消息指出什麼是錯誤的以及在哪裏。如果你不理解它,然後發佈它,因爲我們不是清醒的嚮導,錯誤消息也幫助我們。 –