繁体   English   中英

我的 Java 代码出现越界错误

[英]My Java code is giving me an out of bounds error

我怎样才能找出为什么这总是给我越界错误?

如果有人可以,有人可以就如何缩短代码并使其更有效率给我建议吗? 这是我的计算机科学 II APA 课程。

import java.util.*;
class arrays15
{

/* write a method that will find the largest values
 *  between two ints.
 */
public static int large(int num1, int num2) {
    return Math.max(num1, num2);
}

任务:

/* fun will take two int arrays and for each position
 * it will compare the two values from each array and put the
 * larger of the two in a new array. If there are not two values
 * to compare then take then assume the other value is a zero (0).
 *  
 * Must call another method to find largest.
 */

 public static int[] fun(int[] nums1, int[] nums2) {



    ArrayList<Integer> a = new ArrayList<Integer>();
    ArrayList<Integer> b = new ArrayList<Integer>();
    for(int g = 0; g < nums1.length; g++) {
        a.add(nums1[g]);
    }
    for(int h = 0; h < nums2.length; h++) {
        b.add(nums1[h]);
    }
    for(int i = a.size(); i < b.size(); i++) {
        a.add(0);
    }
    for(int i = b.size(); i < a.size(); i++) {
        b.add(0);
    }
    int[] r = new int[a.size()];
    for(int j = 0; j < r.length; j++) {
        r[j] = large(a.remove(0), b.remove(0));
    }
    return r;
 }

测试

public static void main(String[] args) {
    int[] one = new int[]{1, 2, 3, 4, 5, 6};
    int[] two = new int[]{-1, 3, -4, 8, -5, 6, 7};
    System.out.println(Arrays.toString(one) + " << >> " + Arrays.toString(two));
    System.out.println("maximusArray: " + Arrays.toString(fun(one,two))); // [1, 3, 3, 8, 5, 6, 7]
    System.out.println();

    one = new int[]{-13, -14, -15, 16};
    two = new int[]{};
    System.out.println(Arrays.toString(one) + " << >> " + Arrays.toString(two));
    System.out.println("maximusArray: " + Arrays.toString(fun(one,two)));// {0, 0, 0, 16}
    System.out.println();

    one = new int[]{11, 22, 33};
    two = new int[]{-5, 55, 41, -30, 13};
    System.out.println(Arrays.toString(one) + " << >> " + Arrays.toString(two));
    System.out.println("maximusArray: " + Arrays.toString(fun(one,two)));// {11, 55, 41, 0, 13}
    System.out.println();

}
}

错误消息是:ArrayIndexOutOfBoundsException: 6 at arrays15.fun(Arrays_Lab15_maximusArrays.java:33) at arrays15.main(Arrays_Lab15_maximusArrays.java:52)

  1. 越界错误意味着您可能没有正确访问索引,因此请检查您的哪些数据结构容易受到影响。
  2. 研究您收到的错误消息,因为它至少显示了错误发生的行(如果将其包含在帖子中会更好)。

fun 方法中的第二个 for 循环似乎导致了错误:

for(int h = 0; h < nums2.length; h++) {
    b.add(nums1[h]);
}

为什么引用nums1而不是nums2

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM