Java Notes

Java Example: Console: Adding Machine

Reading in a loop

Scanner hasNext... methods. Scanner has a number of "hasNext" methods to test if the input stream has another value of the requested kind. It returns true if it does, and false if there is no value of that type.

EOF. When there is no more input in a file, there is an End-Of-File (EOF) condition that causes the Scanner hasNextX methods to return false. When reading from the console, the standard way to indicate an EOF is to type a special character combination, eg, Control-Z, or Control-C, or whatever it is on your system. Or there's a button in an IDE that sends an EOF to the program. Because most of the simpler IDEs don't support any way to enter EOF, the easiest way to terminate the program is by entering either a special value (a "sentinel" value), or just typing something that's illegal for that type, which is fine as long as you're not just reading words.

  1 
  2 
  3 
  4 
  5 
  6 
  7 
  8 
  9 
 10 
 11 
 12 
 13 
 14 
 15 
 16 
 17 
 18 
 19 
 20 
 21 
 22 
 23 
 24 
 25 
 26 
// File   : introductory/AddingMachine.java
// Purpose: Read and sum numbers from the console.
// Author : Fred Swartz - 2007-04-05 - Placed in public domain.

package sum;

import java.util.*;

public class AddingMachine {

    public static void main(String[] args) {
        //... Initialization
        double total = 0;          // Sum of all input numbers.
        Scanner in = new Scanner(System.in);

        //... Prompt and read input in a loop.
        System.out.println("As you enter numbers, they will be added.");
        System.out.println("Entering a non-number will stop the program.");
        
        while (in.hasNextDouble()) {
            double n = in.nextDouble();
            total = total + n;
            System.out.println("The total is " + total);
        }
    }
}