Use Scanner to read input from console compute an average of the values in Java
Description
The following code shows how to use Scanner to read input from console compute an average of the values.
Example
//from w w w. j av a2s . c o m
import java.util.Scanner;
public class Main {
public static void main(String args[]) {
Scanner conin = new Scanner(System.in);
int count = 0;
double sum = 0.0;
System.out.println("Enter numbers to average.");
while (conin.hasNext()) {
if (conin.hasNextDouble()) {
sum += conin.nextDouble();
count++;
} else {
String str = conin.next();
if (str.equals("done"))
break;
else {
System.out.println("Data format error.");
return;
}
}
}
System.out.println("Average is " + sum / count);
}
}
The code above generates the following result.