J.E.D.I
5.3 Using JOptionPane to get input
Another way to get input from the user is by using the JOptionPane class which is found in the javax.swing package. JOptionPane makes it easy to pop up a standard dialog
box that prompts users for a value or informs them of something.
Given the following code, import javax.swing.JOptionPane;
public class GetInputFromKeyboard {
public static void main String[] args { String name = ;
name = JoptionPane.showInputDialogPlease enter your name;
String msg = Hello + name + ; JOptionPane.showMessageDialognull, msg;
} }
This will output,
Introduction to Programming I 92
Figure 5.1: Getting Input Using JOptionPane
Figure 5.2: Input florence on the JOptionPane
Figure 5.3: Showing Message Using JOptionPane
J.E.D.I
The first statement, import javax.swing.JOptionPane;
indicates that we want to import the class JOptionPane from the javax.swing package. We can also write this as,
import javax.swing.; The statement,
name = JOptionPane.showInputDialogPlease enter your name; creates a JOptionPane input dialog, which will display a dialog with a message, a
textfield and an OK button as shown in the figure. This returns a String which we will save in the name variable.
Now we create the welcome message, which we will store in the msg variable, String msg = Hello + name + ;
The next line displays a dialog which contains a message and an OK button. JOptionPane.showMessageDialognull, msg;
Introduction to Programming I 93
J.E.D.I
5.4 Exercises
5.4.1 Last 3 words BufferedReader version
Using BufferedReader, ask for three words from the user and output those three words on the screen. For example,
Enter word1:Goodbye Enter word2:and
Enter word3:Hello
Goodbye and Hello
5.4.2 Last 3 words JOptionPane version
Using JOptionPane, ask for three words from the user and output those three words on the screen. For example,
Introduction to Programming I 94
Figure 5.4: First Input
Figure 5.5: Second Input
Figure 5.6: Third Input
Figure 5.7: Show Message
J.E.D.I
6 Control Structures
6.1 Objectives
In the previous sections, we have given examples of sequential programs, wherein statements are executed one after another in a fixed order. In this section, we will be
discussing control structures, which allows us to change the ordering of how the statements in our programs are executed.
At the end of the lesson, the student should be able to: • Use decision control structures if, else, switch which allows selection of specific
sections of code to be executed • Use repetition control structures while, do-while, for which allow executing
specific sections of code a number of times • Use branching statements break, continue, return which allows redirection of
program flow
6.2 Decision Control Structures