Reputation: 1
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
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