计算数组的最大高度

Calculate max Height of array

我正在计算应用程序中插入的 max 高度,它给我一个 ArrayIndexOutOfBound 错误,插入值的时间与数组的长度相同,包括0 索引,但我仍然遇到此错误。

int nrPersons = 3;
double[] height = new double[nrPersons];
double maxHeig = 0;

for (int i = 0; i <= nrPersons; i++) {
    Scanner in = new Scanner(System.in);
    in.useLocale(Locale.US);

    System.out.println("Insert Height");

    height[i] = in.nextDouble();

    if (height[i]> maxHeig)
        maxHeig = height[i];

}

System.out.println("The max Height is: "+maxHeig);

你的问题就在这里

for (int i = 0; i <= nrPersons;i++){

您不需要让 i 达到 nrPersons 的值,因为这将超出范围。 Java 中的数组是从 0 索引的,并定义了元素的数量。所以对于一些数组:

int[] i = new int[3];
i[0] = 0; //fine
i[1] = 0; //fine
i[2] = 0; //fine
i[3] = 0; //**ERROR** Out of bounds

简单的解决方案是使用这种通用语法:

for (int i = 0; i < nrPersons; i++)