【问题标题】:Why am I getting an array out of bounds exception, and why am I only generating the number 0?为什么我得到一个数组越界异常,为什么我只生成数字 0?
【发布时间】:2018-07-13 13:42:00
【问题描述】:
public class ArraysList {

    public static void main(String[] args) {
        int[] scores1;
        int[] scores2;

        scores1 = new int[7];
        scores2 = new int[7];

        int index = 0;
        while (index <= 6) {
            scores1[index] = ThreadLocalRandom.current().nextInt(1, 10 + 1);
            scores2[index] = ThreadLocalRandom.current().nextInt(1, 10 + 1);
            index++;
        }

        System.out.println(scores1[index]);
    }
}

我对为什么会收到异常感到困惑。我可以通过将数组的大小更改为 8 来解决此问题,但我不应该这样做。此外,当它更改为 8 时,输出全为 0。我使用了 3 种不同的方法来获取随机整数,并且每次的结果都是相同的。

【问题讨论】:

  • 因为您的数组中的有效数组索引是 0 到 6 包括在内,而您使用的是 7。

标签: java arrays random


【解决方案1】:

循环之后的行,System.out.println(scores1[index]); - 循环条件是 index &lt;= 6,这意味着 index 现在是 7。因此它超出了范围。我想你想要System.out.println(Arrays.toString(scores1));

【讨论】:

    【解决方案2】:
        int[] scores1;
        int[] scores2;
    
        scores1 = new int[7];
        scores2 = new int[7];
    
        int index = 0;
        while (index <= 6) {
            scores1[index] = ThreadLocalRandom.current().nextInt(1, 10 + 1);
            scores2[index] = ThreadLocalRandom.current().nextInt(1, 10 + 1);
            index++;
        }
    

    对于这一行,你应该像这样重写。因为索引总是从数组中的 0 开始,而您试图在索引 7 处获取数据,而该索引不存在于数组中。

     System.out.println(scores1[index-1]);
    

    【讨论】:

      猜你喜欢
      • 2012-11-08
      • 1970-01-01
      • 2016-06-04
      • 1970-01-01
      • 2018-06-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多