【问题标题】:Calculate max Height of array [duplicate]计算数组的最大高度[重复]
【发布时间】:2015-03-26 14:32:03
【问题描述】:

我正在计算在应用程序中插入的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);

【问题讨论】:

  • i

标签: java indexoutofboundsexception


【解决方案1】:

你的问题来了

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++)

【讨论】:

  • 当然,我的错,无法理解我怎么会错过它。谢谢@Kon
猜你喜欢
  • 2018-02-28
  • 2015-01-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-01-24
  • 2012-08-21
相关资源
最近更新 更多