Java Notes

Example: Dialog: Adding Machine

See Dialog Input Loop for how to read in a loop using dialog boxes.

Example - Adding numbers

This program reads numbers, adding them one by one to the total. At the end of the loop it displays the total.

It reads numbers until the user clicks the Cancel button or clicks the window close box, when JOptionPane.showInputDialog(...) returns null instead of a string. If the user just hits OK without entering anything, the empty string is returned, which is also tested to terminate the loop.

  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 
 27 
 28 
// File   : introductory/AddingMachine.java
// Purpose: Adds a series of numbers.
//          Reads until user clicks CANCEL button, close box, or enters nothing.
// Author : Fred Swartz - 2007-03-05 - Placed in public domain.

import javax.swing.*;

public class AddingMachine {
    public static void main(String[] args) {

        //... Local variables
        double total = 0;      // Total of all numbers added together.

        //... Loop reading numbers until CANCEL or empty input.
        while (true) { // This "infinite" loop is terminated with a "break".
            String intStr = JOptionPane.showInputDialog(null, 
                                        "The current total is " + total +
                                        "\nEnter a number or CANCEL to terminate.");
            if (intStr == null || intStr.equals("")) {
                break; // Exit loop on Cancel/close box or empty input.
            }

            int n = Integer.parseInt(intStr);    // Convert string to int

            total = total + n;                   // Add to total
        }
    }
}

Comments