YRH YRH - 14 days ago 4
Java Question

A java program that takes infinite integer inputs & terminated by a zero whilst taking the input average & total

Write a Java program that will ask you to input numbers and add them until you type a 0. It will then print out

the average of the numbers. Here is a sample of what the output should look like:

Please type a sequence of numbers terminated by a 0





The total was 10.0

You typed in 3 numbers

The average is 3.3333

I decided to teach myself Java & just started programming not too long ago and I'm still working on fully understanding the combinations of what to use to meet the requirements of a program. I've been doing these online challenges and one asks for a program that inputs numbers and add them until a zero has been inputted by the user, on top of that, it also has to show how many total numbers was typed and the average of those. I already started with a while loop and a scanner but am currently struggling & stuck with the problem:

import java.util.Scanner;
public class problem4 {

public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Please type a sequence of numbers terminated by a 0");
int counter = 0;
int num = scan.NextInt();
while (num != 0){
if (num == 0) break;
int total = 0;
double average = 0;
average = total / counter;

System.out.println("The total was " + total);
System.out.println("You typed in " + counter + " numbers");
System.out.println("The average is " + average);


I get 'cannot find symbol' errors on line 8


There are 2 issues in all with your program: 1. You forgot to declare num before using. Declare it and assign a non zero value to it. 2. You should be adding num to total inside the loop so you should also declare it before the loop.

int counter = 0, num = 1, total = 0;
while(num != 0){
    num = scan.nextInt();
    if(num == 0)
    total += num;
double average = (double)total/counter;

A suggestion: Whenever you are dividing an integer with another interger (in this case, total/counter), make sure to cast one to double (or float) to prevent loss of decimal places.