Program that reads 3 numbers with repeat structure with scanner class!

1

How to make an algorithm in Java that reads 3 numbers and gives the mean? I know how to do without using repeat structure, but how to do with repeat structure?

Here is my code below, but it does not have the expected result:

    public class NotaAluno {
    public static void main(String[] args) {
        Scanner entrada = new Scanner(System.in);
        int notaAluno[] = new int[3];
        int i;
        double media = 0;
        for(i = 0; i < notaAluno.length; i++){
            System.out.println("Informe o numero da nota do aluno [" + notaAluno[i]+"]" );
            notaAluno[i] = entrada.nextInt(); 
            media = (notaAluno.length)/ 3;
        }
        System.out.println("A Media dos alunos eh " + media);
    }
}
    
asked by anonymous 15.11.2016 / 01:25

1 answer

3

There are several errors (which I fixed), but the biggest problem is that you are trying to calculate the average inside the loop, you have to find the total and then calculate the mean:

import java.util.Scanner;

class NotaAluno {
    public static void main(String[] args) {
        Scanner entrada = new Scanner(System.in);
        int notaAluno[] = new int[3];
        int total = 0;
        for(int i = 0; i < notaAluno.length; i++) {
            System.out.println("Informe o numero da nota do aluno [" + i + "]" );
            notaAluno[i] = entrada.nextInt(); 
            total += notaAluno[i];
        }
        System.out.println("A Media dos alunos eh " + total / 3);
    }
}

See running on ideone and on CodingGround .

If you do nothing with the values the array is being created needlessly. Only to calculate the average does not need to save individual value.

    
15.11.2016 / 01:33