Prev: Example: Dialog: Capitalize

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 sum. At the end of the loop it displays the sum. If the user clicks the Cancel button or clicks the window close box, 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 
 29 
 30 
 31 
// File   : dialog/AddingMachine.java
// Purpose: Adds a series of numbers.
//          Reads until user clicks CANCEL button.
// Author : Fred Swartz
// Date   : 2005 Oct 19

import javax.swing.*;

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

        //... Local variables
        String intStr;         // String version of the input number.
        int    total = 0;      // Total of all numbers added together.

        //... Loop reading numbers until CANCEL or empty input.
        while (true) {
            intStr = JOptionPane.showInputDialog(null, "Enter an int or CANCEL.");
            if (intStr == null) break;       // Exit loop on Cancel/close box.
            if (intStr.equals("")) break;    // Exit loop on empty input.

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

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

        //... Output the total.
        JOptionPane.showMessageDialog(null, "The total is " + total);
    }
}