Home | JSP | EJB | JDBC | Java Servlets | WAP  | Free JSP Hosting  | Spring Framework | Web Services | BioInformatics | Java Server Faces | Jboss 3.0 tutorial | Hibernate 3.0 | XML
 
 
Hot Web Programming Job

 

Tutorial Categories: Ajax | Articles | JSP | Bioinformatics | Database | Free Books | Hibernate | J2EE | J2ME | Java | JavaScript | JDBC | JMS | Linux | MS Technology | PHP | RMI | Web-Services | Servlets | Struts | UML

[an error occurred while processing this directive]

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

Leave your comment:

Name:

Email:

URL:

Title:

Comments:


Enter Code:

Audio Version
Reload Image
 

Note: Emails will not be visible or used in any way, and are not required. Please keep comments relevant. Any content deemed inappropriate or offensive may be edited and/or deleted.

No HTML code is allowed. Line breaks will be converted automatically. URLs will be auto-linked. Please use BBCode to format your text.

Add This Tutorial To:
  Del.icio.us   Digg   Google   Spurl   Blink   Furl   Simpy   Y! MyWeb 

Current Comments

0 comments so far (
post your own) View All Comments Latest 10 Comments:
  JDO Tutorials
  EAI Articles
  Struts Tutorials
  Java Tutorials
  Java Certification

Tell A Friend
Your Friend Name
Search Tutorials

 

 
 
Browse all Java Tutorials
Java JSP Struts Servlets Hibernate XML
Ajax JDBC EJB MySQL JavaScript JSF
Maven2 Tutorial JEE5 Tutorial Java Threading Tutorial Photoshop Tutorials Linux Technology
Technology Revolutions Eclipse Spring Tutorial Bioinformatics Tutorials Tools SQL
 

Home | JSP | EJB | JDBC | Java Servlets | WAP  | Free JSP Hosting  | Search Engine | News Archive | Jboss 3.0 tutorial | Free Linux CD's | Forum | Blogs

About Us | Advertising On RoseIndia.net  | Site Map

India News

Send your comments, Suggestions or Queries regarding this site at roseindia_net@yahoo.com.

Copyright © 2007. All rights reserved.