Write a program that reads an unspecified number of integers
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
Enter an integer, the input ends if it is 0:
0
No numbers are entered except 0

