Ask Questions?

View Latest Questions

Advertisement


 
 

Dialog Box Input Loop
Posted on: July 26, 2006 at 12:00 AM
Indicating end of input with cancel or close box, a special value, or empty input

Prev: Example: Capitalize | Next:

Java Notes

Dialog Box Input Loop

Indicating end of input with cancel or close box, a special value, or empty input

When reading input in a loop user must have some way of indicating that the end of the input has been reached.

Sentinal value. One way to indicate the end of the input is for the user to enter a special value to indicate that the end has been reached. This generally works, but does eliminate a possible value from the input. This may not be a problem in many cases, but it can be. A common special value is just the empty string.

Special signal - null. A better way to indicate the end of the input is often to do something special. For dialog box input, this could be clicking the close box or hitting the Cancel button. This is easy to test because a null value is returned in those cases. You could have code like  

while (true) {           // Infinite loop must contain a break
    intStr = JOptionPane.showInputDialog(null, "Enter an int or CANCEL."));
    if (inStr == null) {
        break;           // Exit the current loop
    }
    int n = Integer.parseInt(intStr);
    . . .

Alternate if style may be use for exits. Sometimes an if statement is only used to exit from a loop (break), a method (return), or with an exception (throw). In these cases some programmers will omit the braces and write the exit action on the same line. For example.

while (true){           // Infinite loop must contain a break
    intStr = JOptionPane.showInputDialog(null, "Enter an int or CANCEL."));
    if (inStr == null) break;
    int n = Integer.parseInt(intStr);
    . . .

Adding test for empty string. Another common way for the user to indicate the end of the input is simply to hit enter without typing anything. This returns the empty string, a valid string, but one with zero characters in it. Here are two ways to test for the empty string. Note that you have to use the equals(...) method when comparing the content of strings.

    if (inStr.equals("")) ...    // Same as below.
    if (inStr.length() == 0) ... // Same as above.

Here is the same code as in the previous example, with a test for empty input.

while (true){           // Infinite loop must contain a break
    intStr = JOptionPane.showInputDialog(null, "Enter an int or CANCEL."));
    if (inStr == null) break;     // Exit from loop on cancel.
    if (inStr.equals("")) break;  // Exit from loop on empty input.
    int n = Integer.parseInt(intStr);
    . . .

Order matters. The order of the previous tests is important. The null value isn't a string, but a special value that means there is no string. It's the value that's used for all object types to indicate that there is no associated object for that variable. The equals(...) and length() methods both require a string, not a null, to work.

Combining input and testing in one expression. When you're just testing for null, as is common when reading from a text file, it's easier to combine the call and test in the while condition. This tends to be much less readable and has the somewhat unusual embedded assignment in it. Don't try using this unless you feel comfortable with it. For example.

while ((intStr = JOptionPane.showInputDialog(null, "Enter an int or CANCEL.")) != null) {
    . . .

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);
    }
}

Example - Longest Word

This program displays the longest word that was entered.

  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   : loops/LongestWord.java
// Purpose: Display the longest word that was entered.
//          Reads until user clicks CANCEL / close box..
// Author : Fred Swartz
// Date   : 2005 Oct 19

import javax.swing.*;

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

        //... Local variables
        String word;          // Holds the next input word.
        String longest = "";  // Holds the longest word that has
                              //    been found so far.  Start with "".

        //... Loop reading words until the user clicks CANCEL.
        while (true) {
            word = JOptionPane.showInputDialog(null, "Enter a word or CANCEL.");
            if (word == null) break;   // Exit if Cancel or close box clicked.

            //... Check to see if this words is longer than longest so far.
            if (word.length() > longest.length()) {
                longest = word;  // Remember this as the longest.
            }
        }

        //... Output the longest word.
        JOptionPane.showMessageDialog(null, "The longest word was " + longest);
    }
}
Copyleft 2005 Fred Swartz MIT License
Advertisement


DMCA.com