Write a program that reads an unspecified number of integers

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 The total is 5.0 The average is 1.25

Solution

NumbersCount.java

import java.util.Scanner;


public class NumbersCount {

   public static void main(String[] args) {
       Scanner scan = new Scanner(System.in);
       int total = 0;
       int numCount = 0, posCount = 0, negCount =0;
       System.out.println(\"Enter an integer, the input ends if it is 0: \");
      
       while(true){
           int n = scan.nextInt();
           if(n == 0){
               break;
           }
           else{
               if(n < 0){
                   negCount++;
               }
               else{
                   posCount++;
               }
               total = total + n;
               numCount++;
           }
       }
       if(numCount != 0){
       double average = total/(double)numCount;
       System.out.println(\"The number of positives is \"+posCount);
       System.out.println(\"The number of negatives is \"+negCount);
       System.out.println(\"The total is \"+total);
       System.out.println(\"The average is \"+average);
       }
       else{
           System.out.println(\"No numbers are entered except 0\");
       }
   }

}

Output:

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
The total is 5
The average is 1.25

 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 avera

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site