# 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

- The terminating condition, `intStr == null || intStr.equals("")`, must be written with the `null` test first. Reversing the two terms, eg `intStr.equals("") || intStr == null`, will result in a NullPointerException if `intStr` is `null` because they terms are evaluated left to right.

  Short-circuit. The `||` operator is a so called short-circuit operator which doesn't evaluate the right operand if the left operand is left operand determines the result. In the case of `||`, if the left operand is `true`, there's no need to evaluate the right operand because the result must be `true`.

- Format. As with all output of doubles, you might want to control the number of places to the right of the decimal point by calling `String.format(...)`.
- Try-catch. The conversion from String to double may fail, and a NumberFormatException may be thrown. A try-catch should be put around the conversion.