Program that read 3 numbers with repeating structure with scanner class!

Asked

Viewed 512 times

2

How do I make a Java algorithm that reads 3 numbers and averages? I know how to do it without repeating structure, but how to do it with repeating structure?

Follow my code below, but do 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);
    }
}
  • I have tried to do this way media = (notaAluno[i]) / 3 however unsuccessfully

  • You need a vector for that?

1 answer

3


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

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

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

If you’re not gonna do anything with the values array is being created without need. Just to calculate the average do not need to store individual value.

  • bigown Voce mentioned this: "If you’re not going to do anything with the values the array is being created without need" could you explain to me? obg right away.

  • Anything you use, you have to explain the use. If you don’t have an explanation for the use, you shouldn’t use, simple as that. In which case he’s not being used for anything, so there’s no point in putting it there.

  • Thanks I think I understand hehehe

Browser other questions tagged

You are not signed in. Login or sign up in order to post.