Next: Example: initials of a
Up: Unit 02
Previous: Example: initials of a
In Java there are many ways to read strings from input. The simplest one is to
use the predefined method showInputDialog, which is defined in the
class JOptionPane, which in turn is part of the swing
library. Using such a method, we can read input from the keyboard according to
the following schema:
import javax.swing.JOptionPane;
public class KeyboardInput {
public static void main (String[] args) {
...
String inputString = JOptionPane.showInputDialog("Insert a string");
...
System.out.println(inputString);
...
System.exit(0);
}
}
- import javax.swing.JOptionPane; - imports the class
JOptionPane from the library javax.swing
- String inputString = JOptionPane.showInputDialog("Insert a
string");
- creates a dialog window (see figure) showing the message
"Insert a string",
- reads a string from the keyboard,
- returns (a reference to) such a string, and
- assigns the reference to the variable inputString.
- System.exit(0); must be added to the main method when
the predefined library class JOptionPane is used - this is
necessary, since dialog windows are not handled directly by main,
and hence we have to provide an explicit command to terminate them.
Next: Example: initials of a
Up: Unit 02
Previous: Example: initials of a