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.
Sentinel value - not best choice. 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.
Indicating end by clicking on Close Box or Cancel button (null)
Special signal - null. A good way to indicate the end of the input is
often to do something other than enter a sentinal value.
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.
while (true) { // Infinite loop must contain a break intStr = JOptionPane.showInputDialog(null, "Enter an int or CANCEL.")); if (inStr == null) { //... User clicked the Close Box or the Cancel button. break; // Exit the current loop } int n = Integer.parseInt(intStr); . . .
Indicating end by entering "empty" string.
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 || inStr.length() == 0) {
break; // Exit from loop on cancel.
}
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) { . . .