【问题标题】:ArrayIndexOutOfBoundsException computing the averageArrayIndexOutOfBoundsException 计算平均值
【发布时间】:2016-03-18 02:14:30
【问题描述】:

我正在编写 Randall S. Fairman 的这本书,他是 Java 的 3D 天文学,我自己对 Java 的经验有限。他使用这个 LineReader 类而不是 Scanner 或任何东西来获取用户输入。我坚持的练习要求您使用 LineReader 获取数组的值并找到数组中值的平均值。这是我想出的,尽我所能,但它不起作用。当我尝试运行它时,它说

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
at Average.main(Average.java:10) 

代码:

import ui.LineReader;

public class Average {

  public static void main(String[] args) {
     int average;
     int sum = 0;
  for (int j = 0; j < 5; j++) {
    int i = LineReader.queryInt("Give me a number: ");
    int [] M = new int [i];
    sum = sum + M[i];
}
    average = sum/5;
    System.out.println("The average of those numbers is " +average);

    }
}

【问题讨论】:

  • LIneReader 是一个自定义类,不是核心 Java API 的一部分。所以我们不知道那在幕后做了什么。
  • 你需要告诉我们什么不起作用。
  • 当我尝试运行它时,它说 — 线程“main”中的异常 java.lang.ArrayIndexOutOfBoundsException: 1 at Average.main(Average.java:10)
  • 我更新了一个答案。您根本不需要 M[],只需将 'i' 的值加到总和中即可。
  • 所以您的问题与LineReader 无关。例外情况应该首先在您的问题中发布,而不是在难以辨认的评论中。

标签: java arrays indexoutofboundsexception


【解决方案1】:

您不需要int[]M = new int[i]; 行。

只要sum += i;

您更新的代码:

import ui.LineReader;

public class Average {

   public static void main(String[] args) {
     int average;
     int sum = 0;

     for (int j = 0; j < 5; j++) {
        int i = LineReader.queryInt("Give me a number: ");
        sum += i;
     }

     average = sum/5;
     System.out.println("The average of those numbers is " +average);

   }
}

【讨论】:

  • 成功了,谢谢!我不确定如何,我仍然以某种方式访问​​数组吗?
  • 很高兴它对你有用。不,您不再使用数组 - 这是不必要的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-01-14
  • 2012-06-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多