Java Scanner read input from keyboard and calculate average

Introduction

The following program averages a list of numbers entered at the keyboard:


// Use Scanner to compute an average of the values. 
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.");

    // Read and sum numbers.
    while (conin.hasNext()) {
      if (conin.hasNextDouble()) {
        sum += conin.nextDouble();/*from w w  w .  j a  v  a 2 s .  c o m*/
        count++;
      } else {
        String str = conin.next();
        if (str.equals("done"))
          break;
        else {
          System.out.println("Data format error.");
          return;
        }
      }
    }
    conin.close();
    System.out.println("Average is " + sum / count);
  }
}



PreviousNext

Related