Lecture 3 Getting Input From The Keyboard
Lecture 3 Getting Input From The Keyboard
Lecture 3 Getting Input From The Keyboard
BufferedReader class
2. JOptionPane class
graphical user interface
BufferedReader class
Found in the java.io package
Used to get input
1. Add this at the top of your code:
import java.io.*;
2. import java.io.InputStreamReader;
3. import java.io.IOException;
4.
6.
9.
12. try{
15. System.out.println("Error!");
16. }
18. }
19. }
The lines,
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
The statement,
BufferedReader dataIn = new BufferedReader(new
InputStreamReader( System.in) );
declares a variable named dataIn, with the class type
BufferedReader.
The statement,
String name = "";
declares a String variable with identifier name.
The next statement,
System.out.print("Please Enter Your Name:");
outputs a String on the screen asking for the user's
name
The given block defines a try-catch block.
try{ name = dataIn.readLine();
}catch( IOException e ){
System.out.println("Error!");
}
This assures that the possible exceptions that could occur
in the statement name = dataIn.readLine(); will be
catched.
Now going back to the statement,
name = dataIn.readLine();
This value will then be saved to our name variable, which we will use in our final
statement to greet the user,
The statement,
name=JoptionPane.showInputDialog(“Please 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.
The statement,
String msg = "Hello " + name + "!";
creates the welcome message, which we will store in the msg
variable.
The statement,
JOptionPane.showMessageDialog(null, msg);
displays a dialog which contains a message and an OK button.