/ / ArrayIndexOutOfBoundsException výpočet priemeru - java, arrays, indexoutofboundsexception

ArrayIndexOutOfBoundsException výpočet priemeru - java, arrays, indexoutofboundsexception

Pracujem na tejto knihe Randalla S. Fairman, 3D astronómia s Java, s obmedzenými skúsenosťami s Java sám. Použije túto triedu LineReader namiesto skenera alebo čokoľvek, čo sa týka vstupu používateľa. Cvičenie I "m prilepené na vás žiada, aby ste použili LineReader, aby ste získali hodnoty pre pole a našli priemer hodnôt v poli. To je to, čo som prišiel, robím to najlepšie, a to nefunguje." Keď sa to snažím spustiť, hovorí

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

kód:

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

}
}

odpovede:

0 pre odpoveď č. 1

Nepotrebujete to int[]M = new int[i]; linka.

Urob sum += i;

Váš aktualizovaný kód:

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

}
}