我的Java代码给了我一个出界错误

时间:2018-10-08 20:05:57

标签: java computer-science

我如何找出为什么这会不断给我带来错误?

如果有人可以,有人可以给我建议如何缩短代码并使其更高效吗?这是我的计算机科学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 在arrays15.fun(Arrays_Lab15_maximusArrays.java:33) 在arrays15.main(Arrays_Lab15_maximusArrays.java:52)

1 个答案:

答案 0 :(得分:2)

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

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

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

为什么引用nums1而不是nums2