Larry
Larry

Reputation: 77

How to calculate the average of a sequence of integer numbers read from the console?

What is missing in my code in order to calculate the average of the inputted numbers from the user?

public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    int n;
    float average;
    do {
        System.out.print("Enter a number: ");
        n = scanner.nextInt();
        System.out.println("Your number is " + n);
    } while (n != 0);

    if (n == 0) {
        System.out.println("The average is : " + n);
    }

    scanner.close();
}

}

When the user puts in "0" then the programm should calculate the average of the inputted numbers by the user, that is why i wrote "while (n != 0)".

Upvotes: 0

Views: 1135

Answers (2)

HackerBoss
HackerBoss

Reputation: 829

You are not actually using the numbers that you are reading in. A good editor would tell you that before you even ran it. I would look into getting the Eclipse IDE. You will want to do something similar to that suggested by jhenrique. I would say it is probably better to add the numbers as integers and then cast later, so that you do not lose accuracy on floating point additions, which can cause you a lot of grief in some cases (but here you are probably fine). Here is my suggested code, modified from jhenrique's answer:

public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    int n;
    int sum = 0;
    int count = 0;
    do {
        System.out.print("Enter a number: ");
        n = scanner.nextInt();
        System.out.println("Your number is " + n);

        sum += n;
        count++;
    } while (n != 0);

    System.out.println("The average is : " + ((double) sum) / (count - 1));

    scanner.close();
}

double is like float, but more accurate. In the loop, I add each read number to sum and then divide by the number of things read at the end to get the average.

Upvotes: 0

jhenrique
jhenrique

Reputation: 868

You should do something like this: Note that as you have one more number (the zero), then you have to consider it when calculating the average by removing it, because you ask for 0 to finish the program.

public class Teste {

public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    int n;
    double average = 0;
    int qtdNums = 0;
    do {
        System.out.print("Enter a number: ");
        n = scanner.nextInt();
        System.out.println("Your number is " + n);

        average = average + n;
        qtdNums++;
    } while (n != 0);

    if (n == 0) {
        System.out.println("The average is : " + average / (qtdNums - 1));
    }

    scanner.close();
}
}

Upvotes: 1

Related Questions