java 数组索引越界异常

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29775540/
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-11-02 15:55:01  来源:igfitidea点击:

Array Index Out Of Bounds Exception

java

提问by SavageSpud

Been looking around to see if anything could help me out but I don't understand much of what people are answering and anything I do understand doesn't seem to solve the issue! So basically as the title says, I'm getting an array index out of bounds exception and I have no idea why. Any help is greatly appreciated.

一直在环顾四周,看看是否有什么可以帮助我,但我不太明白人们在回答什么,我明白的任何事情似乎都不能解决问题!所以基本上正如标题所说,我得到一个数组索引越界异常,我不知道为什么。任何帮助是极大的赞赏。

Code:

代码:

import javax.swing.*;

public class Array {
    public static void main(String[] args) {
        double height[] = new double[10];
        String heightAsString;
        int i, over18 = 0, under16 = 0;

        for(i = 1; i <= height.length; i++){
            heightAsString = JOptionPane.showInputDialog("Please Enter The Height Of Person " + i);
            height[i] = Double.parseDouble(heightAsString);

            if(height[i] > 1.8){
                over18 += 1;
            }

            if(height[i] < 1.6){
                under16 += 1;
            }
        }

        JOptionPane.showMessageDialog(null,"The Total Number Of People Over 1.8m Is: " + over18 +
        "\nThe Total Number Of People Under 1.6m Is: " + under16);
    }
}

回答by Maroun

Change to

改成

i = 0; i < height.length
    ↑    ↑

Arrays are zero-basedin Java. Meaning that if you have an array of size N, the indexes will be in range [0, N - 1], see The Java? Tutorials - Arrays:

Java 中的数组是从零开始的。这意味着如果您有一个 size 数组N,索引将在 range 内[0, N - 1],请参阅The Java? 教程 - 数组

Each item in an array is called an element, and each element is accessed by its numerical index. As shown in the preceding illustration, numbering begins with 0. The 9th element, for example, would therefore be accessed at index 8.

数组中的每一项都称为一个元素,每个元素都通过其数字索引进行访问。如上图所示,编号从 0 开始。例如,第 9 个元素将因此在索引 8 处被访问。

If you're interested (recommended), go through the JLS - Chapter 10. Arraysas well:

如果您有兴趣(推荐),请阅读JLS - 第 10 章。还有数组

If an array has ncomponents, we say nis the length of the array; the components of the array are referenced using integer indices from 0 to n - 1, inclusive.

如果数组有n分量,我们说n是数组的长度;使用从 0 到 n - 1 的整数索引引用数组的组件,包括。

回答by The Guest

for(i = 1; i <= height.length; i++){
        heightAsString = JOptionPane.showInputDialog("Please Enter The Height Of Person " + i);
        height[i-1] = Double.parseDouble(heightAsString);

        if(height[i-1] > 1.8){
            over18 += 1;
        }

        if(height[i-1] < 1.6){
            under16 += 1;
        }
    }

use height[i-1], because array index starts from 0.

使用 height[i-1],因为数组索引从 0 开始。

回答by silentprogrammer

The problem is with =in i <= height.lengthcondition of the loop

这个问题是=i <= height.length循环的条件

 for(i = 1; i <= height.length; i++){

Change to

改成

 for(i = 0; i < height.length; i++){

height.lengthwill give you number of element in array and array index start from 0to and ends height.length-1so in the last iteration of loop you are trying to access height.lengthindex of array which doesnt exist giving you ArrayIndexOutOfBoundsException.

height.length将为您提供数组中的元素数和数组索引从开始0到结束,height.length-1因此在循环的最后一次迭代中,您试图访问height.length不存在的数组索引,从而为您提供ArrayIndexOutOfBounds异常。

回答by libik

The array is always indexed from zero, therefore it is recommended and clean, to not go around it and use it as it is.

数组总是从零开始索引,因此建议和清洁,不要绕过它并按原样使用它。

So there are two problems with your code - first is, that you start from one, which does not throw exception, but it is not good approach.

所以你的代码有两个问题 - 首先是,你从一个开始,它不会抛出异常,但这不是一个好方法。

Second is, that you reached limit of array because of indexing from zero (array with size 10 is accessed with indexes from 0 to 9).

其次,由于从零开始索引(使用 0 到 9 的索引访问大小为 10 的数组),您达到了数组的限制。

Your code should look like this :

您的代码应如下所示:

    for(i = 0; i < height.length; i++){
        heightAsString = JOptionPane.showInputDialog("Please Enter The Height Of Person " + (i+1));
        height[i] = Double.parseDouble(heightAsString);

        if(height[i] > 1.8){
            over18 += 1;
        }

        if(height[i] < 1.6){
            under16 += 1;
        }
    }

回答by Loco234

The problem isn't in the for loop declaration, it's in this line:

问题不在于 for 循环声明,而是在这一行:

height[i] = Double.parseDouble(heightAsString);

You're starting your for loop i value at 1, you have declared your array as having 10 items, indexed from 0 to 9.

您的 for 循环 i 值从 1 开始,您已将数组声明为具有 10 个项目,索引从 0 到 9。

as a result, when you try and assign the index value 10, you receive an index out of bounds error.

因此,当您尝试分配索引值 10 时,您会收到索引越界错误。

This will solve:

这将解决:

height[i-1] = Double.parseDouble(heightAsString);

回答by Jomy George

In java array index starts from zero. So if you declare an array like

在java数组索引从零开始。所以如果你声明一个数组

double height[] = new double[10];

double height[] = new double[10];

its index starts from zero and ends at 9.

它的索引从零开始,到 9 结束。

But in your code, your index variable(i) starts from 1 and ends at 10(height.length). It leads to two issues, So you are missing first element (0th) in array, and trying to get 10th element (which is not present), and it throws Array Index Out Of Bounds Exception. Change your for loop so that it starts from zero, and ends at 9.

但是在您的代码中,您的索引变量(i)从 1 开始,以 10(height.length)结束。这会导致两个问题,因此您缺少数组中的第一个元素(第 0 个),并尝试获取第 10 个元素(不存在),并且会引发数组索引超出边界异常。更改 for 循环,使其从 0 开始,到 9 结束。

for(i = 0; i < height.length; i++)

for(i = 0; i < height.length; i++)

回答by MateusMnc

Change the following line of code

更改以下代码行

for(i = 1; i <= height.length; i++){

by the following to solve two problems you have:

通过以下来解决您遇到的两个问题:

for(i = 0; i < height.length; i++){

The problem in the first line of code is you are missing the first position (i = 0) of the array. Since every array starts at the 0 position so your last index cannot be equal the length of the array, but 1 index less, and this is why you are having the index out of bound error.

第一行代码的问题是您缺少数组的第一个位置 (i = 0)。由于每个数组都从 0 位置开始,因此您的最后一个索引不能等于数组的长度,而是少 1 个索引,这就是索引超出范围错误的原因。

To better understand consider you have the following 3 position array: [0] [1] [2].

为了更好地理解,请考虑您有以下 3 个位置数组:[0] [1] [2]。

Its length is 3, because there is 3 memory space allocated. But, to access the last space of memory you have to use the index 2, and not 3 as the lenght. Due to that the i < height.lengthshould be used instead of i <= height.length, so you 'i' index will never be the length and never get the index out of bound error.

它的长度是3,因为分配了3个内存空间。但是,要访问内存的最后一个空间,您必须使用索引 2,而不是 3 作为长度。由于应该使用i < height.length而不是i <= height.length,因此您的 'i' 索引永远不会是长度,也永远不会使索引超出范围错误。