/ / ArrayIndexOutOfBoundsException - java、配列、indexoutofboundsexceptionの平均を計算する

ArrayIndexOutOfBoundsException - java、配列、indexoutofboundsexceptionの平均を計算する

私はこの本をRandall S.が手がけています。 Fairman、Javaを使った3D天文学、Javaでの経験が限られています。彼はScannerなどの代わりにこのLineReaderクラスを使用してユーザーの入力を受け取ります。あなたが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);

}
}

回答:

回答№1は0

あなたは 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);

}
}