Lab 4: Getting input from the user by using BufferedReader and JOptionPane
1. BufferedReader: Efficient for reading large amounts of text, part of [Link] package.
More efficient for larger text inputs compared to Scanner.
The BufferedReader class is used for reading text from an input
stream, buffering characters for efficient reading.
Here's a sample program using BufferedReader:
import [Link]; //import the bufferedReader class
import [Link]; //import InputStreamReader calss
import [Link]; //type of exception that can occur during in/output
public class GetInputFromKeyboard
public static void main( String[] args ){
BufferedReader dataIn = new BufferedReader(new
InputStreamReader( [Link]) );
String name = " "; //declares a string variable named initializes it to an empty string
[Link]("Please Enter Your Name:");
try{ //begins a try block, which contains code that might throw an exception
name = [Link](); //reads a line of text from the users input and stores it
in the name variable
}catch( IOException e ){
[Link]("Error!");
[Link]("Hello " + name +"!");
}}
2. JOptionPane: Provides graphical dialog boxes for user input, part of [Link]
package.
The JOptionPane class allows for graphical user input through dialog
boxes.
Here's a sample program using JOptionPane:
import [Link]; //imports the JOptionpane class which
provides standard dialog boxes for user interaction.
public class GetInputFromKeyboard
public static void main( String[] args ){
String name = "";
name = [Link]("Please enter your
name");
String msg = "Hello " + name + "!";
[Link](null, msg);// display a message dialog box
with the greeting message stored in the msg variable. The first argument null
indicates that the dialog box is not tied to any specific frame
}}
Lab Activity
• Identify the output of the following codes; if there are errors try to correct
them
1. [Link](null, ”Here is more useless information”, “title”,
JOptionPane.INFORMATION_MESSAGE);
2. [Link](null, ”really?” , “title”,
JOptionPane.QUETION_MESSAGE);
3. [Link](null, ”your computer has a virus!!!”, “title” ,
JOptionPane.WARNING_MESSAGE);
4. [Link](null, “are you sure “, “title”,
JOptionPane.YES_NO_CANCEL_OPTION);