Code
package javaapplication8;
import java.util.Scanner;
public class JavaApplication8 {
public static void main(String[] args) {
int cantidad = 3;
int[] notas = new int[cantidad];
Scanner teclado = new Scanner(System.in);
System.out.println("\nIntroduzca notas correspondientes (1-10)");
for (int i = 0; i < cantidad; i++) {
int nota;
do {
System.out.print("Nota " + (i + 1) + " : ");
nota = teclado.nextInt();
if (!(nota >= 1 && nota <= 10)) {
System.out.println("\nLa notas deben ir del 1 al 10, introduzca de nuevo");
}
} while (!(nota >= 1 && nota <= 10));
notas[i] = nota;
}
System.out.println("La media de las notas es " + calcularMedia(notas));
}
public static double calcularMedia(int[] arreglo) {
double resultado = 0;
for (int nota : arreglo) {
resultado += nota;
}
return (resultado / arreglo.length);
}
}
Result
Introduzca notas correspondientes (1-10)
Nota 1 : 5
Nota 2 : 5
Nota 3 : 5
La media de las notas es 5.0
BUILD SUCCESSFUL (total time: 5 seconds)
Explanation
We have created this function:
public static double calcularMedia(int[] arreglo) {
double resultado = 0;
for (int nota : arreglo) {
resultado += nota;
}
return (resultado / arreglo.length);
}
Whose utility is to take an arrangement, that no matter how big it is , will return the average of the elements of it.
It should be clarified that the function performed by the average, should be of double
preferably, since the average consists of a division and the result of it can lead to the use of decimals.
We have also left this pair of variables:
int cantidad = 3;
int[] notas = new int[cantidad];
To leave your code so that if the exercise asks you to enter more than three notes, just change the value of cantidad
by the number of notes you need to calculate. And you will not need to make more changes in the code.