CompareTo String Array - 显式工作,但不能隐式地处理循环中的变量



我正在尝试比较数组中的元素。当我在循环中使用变量时,我得到一个越界错误。然而,当我使用显式值代替具有相同值的变量时,它工作正常。

我错过了什么?

问题行是:

int result = (myList[j]).compareToIgnoreCase(myList[j + 1]);

但是如果我使用它,它可以工作(值应该相同(:

int result = (myList[0]).compareToIgnoreCase(myList[1]);

为此搜索了高处和干燥。其他海报有不同的问题。任何意见将不胜感激!下面是虚拟内容的示例:

public class methodSortTest
{
    public static void main(String[] args)
    {
        // Create and load data into array
        String[] myList = new String[2];
        myList[0] = "Charlie";
        myList[1] = "Bravo";
        // Compare, positive/negative
        for (int j = 0; j < myList.length; j++)
        { 
            int result = (myList[j]).compareToIgnoreCase(myList[j + 1]);
            System.out.println("Result is: " + result);
        }
     } 
}

试试这个:更改此内容:

for (int j = 0; j < myList.length; j++)

对此:

for (int j = 0; j < myList.length-1; j++)

问题出在此语句中:

int result = (myList[j]).compareToIgnoreCase(myList[j + 1]);

因为您正在访问j+1

简单的帮助材料:

https://www.geeksforgeeks.org/understanding-array-indexoutofbounds-exception-in-java/

当 j 等于 1 时,myList[j + 1] 的计算结果为 myList[2],从而抛出ArrayIndexOutOfBoundsException。 索引 2 中没有项目,因为您只在索引 0 和 1 处插入了项目。

参考: https://docs.oracle.com/javase/7/docs/api/java/lang/ArrayIndexOutOfBoundsException.html

将 for 循环从

    for (int j = 0; j < myList.length; j++)

    for (int j = 0; j < myList.length-1; j++)  // note the "-1"

最新更新