gpt4 book ai didi

java - 为什么在这段代码中,比较字符串时总是返回 false?

转载 作者:行者123 更新时间:2023-12-02 11:37:13 25 4
gpt4 key购买 nike

为什么if(s.equals(b))总是返回 false
现在我的问题已经解决了!!!! 谢谢大家
这都是因为改变了数组的大小。

 class A {
// this is the function of plaindrome
boolean palindrome(int x) {
// conversion of integer into string
String s = Integer.toString(x);
// conversion of string into char array
char p[] = s.toCharArray();
int j = 0;
char t[] = new char[p.length];
for (int i = (p.length) - 1; i >= 0; i--) {
t[j] = p[i];
j++;
}

String b = new String(t);
if (s.equals(b)) return true;
else return false;
}

public static void main(String args[]) {
A object = new A();
object.palindrome(1221);
}
}

最佳答案

您正在通过长度为 24 的 char 数组反转字符串。 char 是 Java 中的原语,分配为 \u0000。当它转换为字符串时,在您的情况下它会变成 1221\u0000\u0000\u0000 ,这与 1221 不同。通过将 t 初始化为 new char[p.length] 它应该可以更好地工作。

关于java - 为什么在这段代码中,比较字符串时总是返回 false?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48841873/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com