gpt4 book ai didi

java - ArrayIndexOutOfBoundsException 计算平均值

转载 作者:太空宇宙 更新时间:2023-11-04 12:48:26 26 4
gpt4 key购买 nike

我正在编写 Randall S. Fairman 编写的《3D Astronomy with Java》一书,我自己对 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);

}
}

最佳答案

您不需要 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);

}
}

关于java - ArrayIndexOutOfBoundsException 计算平均值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36074971/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com