0

I don't understand where my mistake is. I'm only trying to calculate the average of the inputted numbers. If 0 is the input,it's not calculate to the total of the input numbers.

import java.util.Scanner;
public class AverageOfNumbers {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        double average=0.0;
        int nrofnumbers=0;
        int sum=0;
        while(true){
            System.out.println("Give a number: ");
            int input = Integer.valueOf(scanner.nextLine());
            if(input == 0){
                break;
         
            }else{
                sum = sum+input;
                nrofnumbers=nrofnumbers + 1;
            }
        
        }
        average = sum/nrofnumbers;
        System.out.println("Average of the numbers: "+average);
    }
}
  • Please give more information about what you are trying to do: Do you want to make an average of all the numbers read and stop when 0 is encountered? – David Buzatu Jul 18 '20 at 16:12
  • You should clarify your issue.. Is your problem that the program exits on 0 when you only want it to skip that input? – MarsAtomic Jul 18 '20 at 16:12
  • You have incremented ```nrofnumbers``` inside the ```else``` statement only. Increment ```nrofnumbers``` inside ```if``` statement also – shayanmalinda Jul 18 '20 at 16:13
  • Otherwise you can increment ```nrofnumber``` outside the ```if``` statment – shayanmalinda Jul 18 '20 at 16:14

0 Answers0