Java回文字符串检测程序判定结果异常的修正方案
Fixing Your Java Palindrome Detection Program
Hey there! Let's sort out why your palindrome detection program is giving wrong results, even though it compiles just fine. The issue boils down to a super common Java gotcha with string comparison.
The Root Cause
Your code's critical mistake is using == to compare the lowercase versions of a and rev. In Java:
==checks if two string variables point to the exact same object in memory, not whether their content matches.- Even if
aandrevhave identical characters (like with "level"), they're separate string objects (one's your input, the other's built by your loop), so==will always returnfalsehere.
The Fix
Replace the == check with the equals() method, which compares the actual content of the strings:
if (a.equals(rev)) { System.out.println("It is a palindrome"); } else { System.out.println("It is not a palindrome"); }
Optional Improvements (For Cleaner, More Efficient Code)
While we're polishing things up, here are a few tweaks to make your code better:
- Use
StringBuilderfor reversed strings: String concatenation in a loop creates unnecessary intermediate string objects.StringBuilderis more efficient:StringBuilder revBuilder = new StringBuilder(); for (int i = b - 1; i >= 0; i--) { revBuilder.append(a.charAt(i)); } String rev = revBuilder.toString(); - Skip the loop entirely: Java's
StringBuilderhas a built-inreverse()method that does the work for you:String rev = new StringBuilder(a).reverse().toString(); - Fix the
mainmethod signature: The standardmainmethod should accept aString[] argsparameter. Some Java environments might throw errors without it, even if the code compiles:public static void main(String[] args) { // Your code here }
Full Corrected Code
Here's the complete, working version of your program with all core fixes applied:
import java.util.Scanner; class Palindrome_string { public static void main(String[] args) { System.out.println("\f"); Scanner sc = new Scanner(System.in); System.out.println("Enter a string"); String a = sc.nextLine(); int b = a.length(); String rev = ""; for (int i = b - 1; i >= 0; i--) { char c = a.charAt(i); rev = rev + c; } System.out.println("Original word "+a); System.out.println("Reversed word "+rev); a = a.toLowerCase(); rev = rev.toLowerCase(); if (a.equals(rev)) { System.out.println("It is a palindrome"); } else { System.out.println("It is not a palindrome"); } sc.close(); } }
内容的提问来源于stack exchange,提问作者Mr Gubbo
相关产品推荐
相关产品推荐

