You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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 a and rev have identical characters (like with "level"), they're separate string objects (one's your input, the other's built by your loop), so == will always return false here.

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 StringBuilder for reversed strings: String concatenation in a loop creates unnecessary intermediate string objects. StringBuilder is 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 StringBuilder has a built-in reverse() method that does the work for you:
    String rev = new StringBuilder(a).reverse().toString();
    
  • Fix the main method signature: The standard main method should accept a String[] args parameter. 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.28 17:52:51