Question
Write a Java program that can add up and count a series (any number) of integers entered by the user. Use a loop and stop
Write a Java program that can add up and count a series (any number) of integers entered by the user. Use a loop and stop the loop when the user enters a value of zero. Then, display the count, total and average. Express the average accurate to three decimal places.
SAMPLE RUN Enter a number or 0 to quit: 12 Enter a number or 0 to quit: 5 Enter a number or 0 to quit: 41 Enter a number or 0 to quit: 0 The total of those 3 numbers is 58. The average is 19.333.
Here is my code:
public static void main(String[] args) int count = 0; int total = 0; float average = 0; int number = 0; Scanner input = new Scanner(System.in); //a do while loop is used here do { System.out.print("Enter a number or enter 0 to quit: "); number = input.nextInt(); if (number > 0) { count++; total = total + number; } } while (number > 0); if (count != 0) //the average will now be calculated average = total / count; System.out.println("The total of those " + count + " numbers is " + total); System.out.println(); System.out.printf("The average is %.3f ", average); } }
The output looks fine, but the average should be 19.333 instead of 19.000. What am I doing wrong?
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started