正整数回文判断代码异常排查:输入121判定结果与预期不符
Hey there! I spot the exact issue with your code right away—let’s break it down simply.
The problem is in this critical line:
if(arr == num) {
In Java, when you use the == operator with String objects, you’re comparing their memory addresses, not the actual text content they hold. Even though arr and num print out the same characters ("121"), they’re two separate String objects stored in different spots in memory. That’s why == returns false here, even though the output looks identical.
The Quick Fix
Instead of ==, use the equals() method—this is the correct way to compare the content of String objects in Java:
if(arr.equals(num)) {
The equals() method is specifically designed to check if every character in the two strings matches perfectly, which is exactly what you need for your palindrome check.
Modified Full Code
Here’s your updated code with the fix (plus a small best-practice addition):
import java.util.Scanner; public class CheckPalindrome3 { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.println("Enter your number :"); String num = input.nextLine(); String arr = ""; for(int i = num.length() - 1 ; i >= 0;i--) { arr = arr + num.charAt(i); } System.out.println(arr+"\n"+num); if(arr.equals(num)) { System.out.println("Yes that's a Palindrome !!"); } else { System.out.println("No that's not a Palindrome !!"); } input.close(); // Clean up the scanner to avoid resource leaks } }
内容的提问来源于stack exchange,提问作者Mr newbie

