2. Write a program that reads in ten whole numbers and outputs the sum and avera
ID: 3603999 • Letter: 2
Question
2. Write a program that reads in ten whole numbers and outputs the sum and average of all the numbers greater than or equal to zero (i.e. all positive numbers or 0) Note, if no positive numbers or zeros are entered, your program should print a message that average of positive numbers could not be computed. the sum and average of all the numbers less than zero (which will be negative only) Note, if no negative numbers are entered, your program should print a message that average of negative numbers could not be computed the sum and average of all numbers, i.e. including negative, positive or zero. The user enters the ten numbers just once each and the user can enter them in any order (i.e. a mix of positive and negative numbers, or zero). Your program should NOT ask the user to enter the positive and negative numbers separately Also, use a do while loop to make your program interactive so that it allows users to run the program as often as the user wishes. See Sample Run below on the next page:Explanation / Answer
NumbersCheck.java
import java.util.Scanner;
public class NumbersCheck {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
char choice = 'y';
do {
int n, posCount = 0, negCount = 0;
int total = 0, posTotal = 0, negTotal = 0;
System.out.println("Enter the ten numbers: ");
for(int i=0;i<10;i++) {
n = scan.nextInt();
total+=n;
if(n < 0) {
negCount++;
negTotal+=n;
} else {
posCount++;
posTotal+=n;
}
}
System.out.println("Total: "+total);
System.out.println("Average: "+(total/10.0));
if(posCount == 0){
System.out.println("The average of positive numbers could not be computed");
} else {
System.out.println("Positive numbers total: "+posTotal);
System.out.println("Positive numbers average: "+(posTotal/(double)posCount));
}
if(negCount == 0){
System.out.println("The average of negative numbers could not be computed");
} else {
System.out.println("Negative numbers total: "+negTotal);
System.out.println("Negative numbers average: "+(negTotal/(double)negCount));
}
System.out.println("Do you want to continue (y or n): ");
choice = scan.next().charAt(0);
} while (choice == 'y' || choice == 'Y');
}
}
Output:
Enter the ten numbers:
11 22 33 -33 -44 -55 66 7 8 9
Total: 24
Average: 2.4
Positive numbers total: 156
Positive numbers average: 22.285714285714285
Negative numbers total: -132
Negative numbers average: -44.0
Do you want to continue (y or n):
y
Enter the ten numbers:
1 2 3 4 5 6 7 8 9 10
Total: 55
Average: 5.5
Positive numbers total: 55
Positive numbers average: 5.5
The average of negative numbers could not be computed
Do you want to continue (y or n):
n
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.