[英]ArrayIndexOutOfBoundsException computing the average
我正在研究Java 3D天文学Randall S. Fairman的这本书,而我本人对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);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.