Make the average of three values of an array in Java

2

I want to get the average of three notes entered in an array:

Code:

``````System.out.println("\nIntroduca notas correspondientes(1-10)");

for(j=0;j<3;j++)
{
do{
System.out.print("Nota "+(j+1)+" : ");
notas[j]=tecla.nextInt();
if(notas[j]<1 || notas[j]>10)
{
System.out.println("\nLa notas deben ir del 1 al 10, introduzca de nuevo");
}
}while(notas[j]<1 || notas[j]>10);
}
objAlumnos.setNotas(notas);
``````

But I have that part of code to enter the notes, but now I do not know how to take each note to add it and divide it by 3.

asked by Mario Guiber 26.08.2017 в 17:44
source

2

Code

``````package javaapplication8;

import java.util.Scanner;

public class JavaApplication8 {

public static void main(String[] args) {

System.out.println("\nIntroduzca notas correspondientes (1-10)");

for (int i = 0; i < cantidad; i++) {

int nota;

do {

System.out.print("Nota " + (i + 1) + " : ");

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

for (int nota : arreglo) {
}

}

}
``````

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

for (int nota : arreglo) {
}

}
``````

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