user1435926
user1435926

Reputation: 1

calculate average with user input

I'm writing a program to calculate average with user input.

import java.util.Scanner;
public class mean
{   
    static Scanner input = new Scanner (System.in);
    public static void main (String[] args)
    {
    double i;
    double sum = 0;
    int count = 0;
    do
    {
        System.out.println("input");
        i = input.nextDouble();
        sum = sum + i;
        count++;
    }while (i != 0);
    System.out.println("sum is " + sum + " count is " + (count - 1));
    System.out.println("average is " + sum / (count - 1));
}
}

here if I input 0, it will calculate. but if there is 0s in the list. can somebody guide me a great while condition?

Upvotes: 0

Views: 29398

Answers (2)

Amber Wolf
Amber Wolf

Reputation: 1

instead of sum = sum + i an easier way would be sum += i

Upvotes: 0

Nadeem Douba
Nadeem Douba

Reputation: 1092

You could ask the scanner whether or not the next token that the scanner is reading is a double and break if it isn't. Example below:

import java.util.Scanner;
public class mean
{   
    static Scanner input = new Scanner (System.in);
    public static void main (String[] args)
    {
    double i;
    double sum = 0;
    int count = 0;
    while(input.hasNextDouble())
    {
        System.out.println("input");
        i = input.nextDouble();
        sum = sum + i;
        count++;
    }
    System.out.println("sum is " + sum + " count is " + (count));
    System.out.println("average is " + sum / (count));
}
}

If the user inputs a non-digit character (e.g. not '+', '-', 0-9, '.', etc.), the loop will break because input.hasNextDouble() will return false.

Upvotes: 2

Related Questions