Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write a program that reads an unspecified number of nonnegative integers, determ

ID: 3698874 • Letter: W

Question

Write a program that reads an unspecified number of nonnegative integers, determines how many values have been read, and computes the total and average of the input values. The total will be displayed as an integer. The average will be displayed as a floating-point number with 2 digits after the decimal place. Your program should let the user know that he/she will enter input -1 when he/she finishes entering numbers. This sentinel value -1 at the end of the input should NOT be included when calculating the total and the average of the input values. If the user enters only -1 as the input, a message “no numbers are entered except -1” will be displayed. No other output should be displayed.

Explanation / Answer

NumbersCountTest.java

import java.util.Scanner;

public class NumbersCountTest {

public static void main(String[] args) {

Scanner scan = new Scanner(System.in);

int total = 0;

int numCount = 0;

System.out.println("Enter an integer, the input ends if it is -1: ");

while(true){

int n = scan.nextInt();

if(n == -1){

break;

}

else{

total = total + n;

numCount++;

}

}

if(numCount != 0){

double average = total/(double)numCount;

System.out.println("The total is "+total);

System.out.printf("The average is %.2f ",average);

}

else{

System.out.println("No numbers are entered except -1");

}

}

}

Output:

Enter an integer, the input ends if it is -1:
10
20
30
40
55
556
64
3
2
-1
The total is 780
The average is 86.67

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote