有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

Java处理数组索引越界

我正在编写一个算法,将一个数n与元素n+1n-1进行比较

这意味着第一次和最后一次检查失败,因为数组。长度+1将超出范围,数组[0-1]也将超出范围。我试图找到一种方法来阻止程序抛出数组索引越界异常,但我不知道如何做到这一点。我最初的计划是检查数组[0-1]和长度+1是否始终为空,如下所示:

numbers[x-1] == null

但这不起作用,因为int与null不匹配。任何关于如何补救的想法都将不胜感激


共 (5) 个答案

  1. # 1 楼答案

    迭代从index1开始,以索引array.length - 1结束

    for(int i=1;i<array.length-1;i++){
       int prev = array[i-1];
       int current = array[i];
       int next = array[i+1];
    }
    
  2. # 2 楼答案

    我只需要检查阵列的边缘:

    int prev = -1;
    int next = -1;
    for (int i=0; i<array.length; i++) {
        if (i>0)
            prev = array[i-1];
        if (i < array.length - 1)
            next = array[i+1];
        else
            next = -1;
        // now do whatever you wish to do with array[i], prev and next
    }
    

    在这种情况下,我选择-1表示“null”值。根据数组中的值的范围,可以使用其他值

  3. # 3 楼答案

    除了其他答案建议的长度检查之外,您还可以创建一个更大的数组元素,以便最后一个元素n+1仍然是有效的数组位置,但标记数组的结束。这样,您就可以忘记所有长度检查,这将提高算法的速度-如果这很重要的话。否则,我将执行长度检查

  4. # 4 楼答案

    您应该使用“if”语句检查索引是否在范围内:

    if (x >= 0 && x < numbers.length)
        numbers[x] = someNumber
    
  5. # 5 楼答案

    可用于将数组与最后一个和下一个元素进行比较的内容:

    for(int index=1;index<array.length-1;index++){
        if (number > numbers[index - 1] && number < numbers[index + 1]) {
            System.out.println("Number is between " + (index - 1) + " and " + (index + 1));
        }
     }