我的Java代码给了我一个越界错误 [英] My Java code is giving me an out of bounds error

查看:58
本文介绍了我的Java代码给了我一个越界错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何才能找出为什么它总是给我出界错误?

如果有人能做到这一点,有没有人能给我一些建议,告诉我如何缩短代码,使其更高效?这是为我的计算机科学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();

}
}
错误消息为: ArrayIndexOutOf边界异常:6 在arrays15.fun(Arrays_Lab15_maximusArrays.java:33) 在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

这篇关于我的Java代码给了我一个越界错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆