我如何克服此代码中的 java.lang.ArrayIndexOutOfBoundsException: 2 ?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9848709/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-16 08:33:39  来源:igfitidea点击:

How do I overcome java.lang.ArrayIndexOutOfBoundsException: 2 in this code?

javaarraysfor-loopwhile-loopboolean

提问by user1215225

When I tested this code, it gave me java.lang.ArrayIndexOutOfBoundsException: 2 The code isn't finished yet but this is what I am trying to do: A program that asks the user for two numbers. Print all numbers from the smaller number to the larger number (inclusive) in a random order. Using this order, find the largest sum of 2 numbers adjacent to one another. Could some please point out to me what needs to be fixed as well as how to fix it? Thanks.

当我测试这段代码时,它给了我 java.lang.ArrayIndexOutOfBoundsException: 2 代码还没有完成,但这就是我想要做的:一个要求用户输入两个数字的程序。以随机顺序打印从小数到大数(含)的所有数字。使用此顺序,找出彼此相邻的 2 个数字的最大和。能否请一些人向我指出需要修复的内容以及如何修复它?谢谢。

 boolean isNum = false;
    int in1 = 0;
    int in2 = 0;
    int size = 0;
    int largestsum = 0;
    while (!isNum) {
        try {
            System.out.print("Enter a number: ");
            in1 = Integer.parseInt(in.readLine());
            boolean isSame = false;
            while (!isSame) {
                System.out.print("Enter a number: ");
                try {
                    in2 = Integer.parseInt(in.readLine());
                    if (in1 != in2) {
                        isSame = true;
                    } else {
                        System.out.println("Same number.");
                    }
                } catch (NumberFormatException nfe) {
                    System.out.println("Not a number.");
                }
            }
            isNum = true;
        } catch (NumberFormatException nfe) { //catches error
            System.out.println("Not a number."); //informs user of the error
        }
    }
    if (in1 > in2) {
        size = in1 - in2 + 1;
        int[] num = new int[size];
        for (int i = 0; i < size; i++) {
            num[i] = in2 + i;
        }
        int[] order = new int[size];
        boolean[] used = new boolean[size];
        for (int i = 0; i < size; i++) {
            int r = (int) ((size) * (Math.random()));
            while (used[r]) {
                r = (int) ((size) * Math.random());
            }
            order[i] = r; //fill array
            used[r] = true; //r is now used
        }
        for (int i = 0; i < size; i++) {
            if (num[order[i]] + num[order[i + 1]] > largestsum) {
                largestsum = num[order[i]] + num[order[i + 1]];
            }
        }

采纳答案by wattostudios

The last forloop will overflow when i=size-1

当 i=size-1 时,最后一个for循环将溢出

In your question, you want to get the sum between 2 adjacent numbers. Your logic in the last forloop says that you calculate the sum by adding number ito i+1. The last item in your array is at position size-1, so when you then try to add this to the next adjacent number, (size-1)+1overflows the array.

在您的问题中,您想获得两个相邻数字之间的总和。您在最后一个for循环中的逻辑表示您通过将数字i添加到i+1来计算总和。数组中的最后一项位于size-1位置,因此当您尝试将其添加到下一个相邻数字时,(size-1)+1 会溢出数组。

To fix the problem, your last for loop should only continue until i<size-1, like so...

为了解决这个问题,你的最后一个 for 循环应该只持续到i<size-1,就像这样......

    for (int i = 0; i < size-1; i++) {
        if (num[order[i]] + num[order[i + 1]] > largestsum) {
            largestsum = num[order[i]] + num[order[i + 1]];
        }
    }

With this fixed logic, the largest item in the forloop is size-2, and when you add 1 to it (for the next adjacent number), it will choose item (size-2)+1, which is the last item in the array, rather than overflowing the array.

使用这个固定逻辑,for循环中最大的项目是size-2,当你加 1 时(对于下一个相邻的数字),它会选择项目(size-2)+1,这是最后一个项目数组,而不是溢出数组。

回答by VeeArr

My guess is the problem is in your very last for loop. Since ordercan contain values ranging from 0to size, num[order[i]]is always valid, but in the case where order[i]==size, num[order[i+1]]is out of bounds.

我的猜测是问题出在您的最后一个 for 循环中。由于order可以包含范围从0到 的值sizenum[order[i]]因此始终有效,但在 的情况下,order[i]==size,num[order[i+1]]超出范围。