无法在 Java 中 运行 回文程序

Unable to run Palindrome program in Java

这是我的 Java 代码,用于查找字符串的回文。它显示 o/p 为“回文”,即使我输入的 i/p 不是。谁能帮帮忙

String a = sc.next();
char b[] = a.toCharArray();
char d[] = b;
int size = a.length();
int beg=0,end=size-1;

while(beg<=end)
{
    char temp = b[beg];
    b[beg] = b[end];
    b[end] = temp;
    beg++;
    end--;
}

 if(d.equals(b))
    {
     System.out.print("Palindrome");
    }
else
    System.out.print("Not a Palindrome");

您的实施存在一些问题。首先-

while(beg<=end)
{
    char temp = b[beg];
    b[beg] = b[end];
    b[end] = temp;
    beg++;
    end--;
}

仔细调试看看在这个while循环的最后是否真的有d[]作为b[]的反转

其次,

 if(d.equals(b))
    {
     System.out.print("Palindrome");
    }

如果两个数组中的所有数组元素都相同,这不是比较的正确方法。如果您查看实现或尝试使用一些示例数组,您将能够自己看到它。

要检查回文,非常简单的方法是使用 StringBuilder 反转字符串并检查它是否等于原始字符串 -

    Scanner sc = new Scanner(System.in);
    String a = sc.next();
    String aRev = new StringBuilder(a).reverse().toString();


    if (a.equals(aRev)) {
        System.out.print("Palindrome");
    } else {
        System.out.print("Not a Palindrome");
    }

另一种更好的方法是 运行 从字符串的开头到中间进行循环,并从结尾到中间保留一个索引。然后检查正向索引和反向索引。

    Scanner sc = new Scanner(System.in);
    String a = sc.next();

    boolean palindrome = true;

    for (int i = 0; i < a.length() / 2; i++) {
        if (a.charAt(i) != a.charAt(a.length() - i - 1)) {
            palindrome = false;
            break;
        }
    }

    System.out.println(palindrome ? "Palindrome" : "Not Palindrome");

试试这个代码,它按预期工作。

public class Main {
    public static boolean isPalindrome(String str) {
        int i = 0, j = str.length() - 1;

        // The following condition checks if the decreasing index 
        // is larger than the increasing one, 
        // which happens at the middle of the string.
        // This is done, because there is no need to iterate over,
        // the entire string.
        while(j > i){ // Non-matching character found, return early.
            if(str.charAt(i) != str.charAt(j)){
                return false;
            }
            j--; // Ending index decreases.
            i++; // Starting index increases.
        }
        // If the loop finishes, without returning all characters of the string match.
        return true;
    }
    public static void main(String[] args) {
        String string = "Non-palindrome";
        String palindrome = "WoW";
        System.out.println("String " + string + " is palindrome: " + isPalindrome(string));
        System.out.println("String " + palindrome + " is palindrome: " + isPalindrome(palindrome));
    }
}

当运行时,以上代码输出:

String Non-palindrome is palindrome: false
String WoW is palindrome: true

char d[] = b;

您为 b 创建了别名 d。因此,本质上,bd 指的是同一个 char-Array。修改b和修改d没有区别。因此,比较 d.equals(b) 将始终产生 true.