Count positive and negative numbers

The problem

Write a program that reads an unspecified number of integers, determines how many positive and negative values have been read, and computes the total and average of the input values (not counting zeros). Your program ends with the input 0. Display the average as a floating-point number. Here is a sample run:

Enter an integer, the input ends if it is 0: 1 2 -1 3 0
The number of positives is 3
The number of negatives is 1

Breaking it down

Reading input from the user and splitting it on a space will give us a String array. To count negative and positive numbers we will create a stream from the array and then use a lambda expression to filter values greater than zero and less than zero. Java 8 has a special object for collecting statistics such as count, min, max, sum, and average named SummaryStatistics. So for total and average, mapToDouble to DoubleSummaryStatistics .summaryStatistics() will give us those values for the user's input. Finally we will output the values to the console.

public static void main(String[] args) {

    System.out.print("Enter an integer, the input ends if it is 0: ");
    Scanner input = new Scanner(System.in);

    String[] values = input.nextLine().split("\s+");

    input.close();

    long positive = Stream.of(values).mapToInt(Integer::parseInt)
            .filter(p -> p > 0).count();

    long negative = Stream.of(values).mapToInt(Integer::parseInt)
            .filter(p -> p < 0).count();

    DoubleSummaryStatistics stats = Stream.of(values)
            .mapToDouble(Double::parseDouble).summaryStatistics();

    double total = stats.getSum();
    double average = stats.getAverage();

    System.out.println("The number of positives is " + positive);
    System.out.println("The number of negatives is " + negative);
    System.out.println("The total is " + total);
    System.out.println("The average is " + average);
}

Output

Enter an integer, the input ends if it is 0: 1 2 -1 -1 2 33 -2
The number of positives is 4
The number of negatives is 3
The total is 34.0
The average is 4.857142857142857