在我的代碼中,我正在測試回文,但我的輸入變量不會在每次迭代時重置。測試第一次運行完美,但使用相同的輸入,它出現(xiàn)錯誤。Scanner input = new Scanner(System.in);int i;System.out.print("Enter a string: ");String pal = input.nextLine();String reverse = "";boolean isFalse = false;while (!isFalse) { if (pal.isEmpty()) { System.out.println("Empty line read - Goodbye!"); isFalse = true; } if (pal.length() > 0) { for (i = pal.length() - 1; i >= 0; --i) { reverse = reverse + pal.charAt(i); } if (pal.equals(reverse)) { System.out.println(pal + " is a palidrome"); System.out.println(); } else { System.out.println(pal + " is not a palidrome"); System.out.println(); } System.out.print("Enter a string: "); pal = input.nextLine(); }}pal 是輸入變量。在調試時,我打印了pal的結果。1331 以回文形式出現(xiàn),但當我重新進入 1331 時,程序輸出了一條錯誤語句。有什么建議?編輯:我在while循環(huán)上方添加了其余代碼
1 回答

浮云間
TA貢獻1829條經驗 獲得超4個贊
您應該reverse通過reverse = "";在 for 循環(huán)之前寫入來重置變量:
reverse = "";
for (i = pal.length() - 1; i >= 0; --i) {
reverse += pal.charAt(i);
}
添加回答
舉報
0/150
提交
取消