简体   繁体   中英

Java. Trying to calculate average of positive numbers only, also displaying a message if no positive numbers are entered

I am trying to do an exercise and cannot figure out how to calculate the average of positive numbers only and also how to display a certain message if no positive numbers are entered. I want the message to be displayed only if there are no positive numbers entered. Thank you

import java.util.Scanner;

public class AverageOfPositiveNumbers {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        int entries = 0;
        Double average = 0.0;
        Double sum = 0.0;


        while (true) {
            int number = Integer.valueOf(scanner.nextLine());
            if (number == 0) {
                System.out.println(average);
                break;
            }
            if (number > 0) {

                entries = entries + 1;
                average = sum / entries;
                sum = sum + number;
            }
            if (number < 0) {
                System.out.println("Cannot calculate the average.");
            }

        }

    }
}

You only need two variables to determine the average. The number of elements (a count ) and the sum of the positive values. Calculate the average once you are done getting the elements. Something like,

Scanner scanner = new Scanner(System.in);
int count = 0;
int sum = 0;
while (true) {
    int number = Integer.parseInt(scanner.nextLine());
    if (number == 0) {
        break;
    } else if (number > 0) {
        count++;
        sum += number;
    }
}
if (count > 0) {
    System.out.printf("The average is %.2f%n", sum / (double) count);
} else {
    System.out.println("Cannot calculate the average.");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM