gpt4 book ai didi

java - if 语句条件没有通过但应该是!? (java)

转载 作者:行者123 更新时间:2023-11-30 02:34:23 25 4
gpt4 key购买 nike

if (value.compareTo(elementData[size]) >= 0) {
elementData[size + 1] = value;
size++;
} else if (value.compareTo(elementData[0]) <= 0) {
for (int i = size; i >= 0; i--) {
elementData[i + 1]= elementData[i];
}

elementData[0] = value;
size++;
}

第一个 if 语句应该从compareTo 返回一个正数。我已经调试并确认它确实返回一个正数,但它没有进入 block 。

我正在比较类似“str1”“str2”...等的字符串。它工作正常,直到我到达“str10”并且必须将其与“str9”进行比较。据说“str10”小于“str9”,这有什么意义吗?

每 10 次迭代就会发生一次。所以我的数组看起来像 [str0, str1, str10...str19,str2, str20, str21, ... str29..etc]

最佳答案

考虑如何string使用 compareTo(String anotherString) 时比较值.

Compares two strings lexicographically. The comparison is based on the Unicode value of each character in the strings. The character sequence represented by this String object is compared lexicographically to the character sequence represented by the argument string. The result is a negative integer if this String object lexicographically precedes the argument string. The result is a positive integer if this String object lexicographically follows the argument string. The result is zero if the strings are equal; compareTo returns 0 exactly when the equals(Object) method would return true.

正如你所看到的,当 "str10" 时会发生什么与 "str9" 进行比较'1' 的 Unicode 值在"str10"小于 Unicode 值 '9'"str9"这就是为什么你得到结果 "str10" 大于"str9" .

您可以研究 Alphanum 算法作为替代方案。

关于java - if 语句条件没有通过但应该是!? (java),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43485380/

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