How to Use Scanner to Calculate the Average of a Group of Numbers
From Java Example Source Code
Contents |
[edit] Overview - How to Use Scanner to Calculate the Average of a Group of Numbers
This Java example program shows how to use scanner to calculate the average of a group of numbers.
[edit] Java Source Code
- Package: example.scanner
- File: MainClass.java
package example.scanner; /** *Output: */ import java.util.Scanner; public class MainClass { 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); } }
[edit] What Result You Can Get
Run the program, you will get:
Enter numbers to average.
[edit] Required External Libraries and/or Files for this Java Example
Need nothing.
[edit] How to Run this Java Example Program
We recommend running this Java example program with Eclipse.
For assistance in working with Eclipse, please see How to Run Java Program with Eclipse.
It's fairly easy.
[edit] Question & Answer
Any question?
Click edit and post your question or answer here.
