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 don't know how to take each note to add it and divide it by 3.
Code
Result
Explanation
We have created this function:
Whose utility is to take an array, which regardless of its size , will return the average of its elements.
It should be clarified that the function that performs the mean should
double
preferably be of type, since the mean consists of a division and the result thereof may involve the use of decimals.We have also left this couple of variables:
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 won't need to make any more changes to the code.See an example
A simpler way to carry out this exercise (Ivan Botero's proposal is correct) would be to use a variable
contador
that accumulates the notes. Then use the variablemedia
to assign it as a value, the variablecontador
between 3.The code would look like this: