Capturing keyboard in a Java console program is very simple and needs only some lines of code. Console programs are run in a window by entering program name and turns on command line. Interactivity is embedded by giving text prompts to request input, and capturing information user forms on keyboard.
• Open Java code in any editor.
• Add below given line at top of file.
import java.io.* ;
• Add below given code to capture keyboard input. These lines state a BufferedReader that reads text from "standard input", and a String to save input.
BufferedReader inputReader = new BufferedReader(new InputStreamReader(System.in)) ;
String inputData ;
• Add following lines to code to capture keyboard input. This captures keyboard input from user and saves in "inputData" variable, and displays error if reading input fails. Input is read when user presses "Enter" key and readLine reads whole line ending with a line feed or carriage return.
try {
String inputData = inputReader.readLine();
}
catch(IOException e) {
System.out.println("Error reading keyboard input") ;
}
• Use parse functions to convert String to a different form if required. For instance, if program prompts user for a floating point value, add following to convert inputData to a float:
float f ;
try{
f = Float.parseFloat(inputData) ;
}
catch(NumberFormatException e) {
System.out.println("Invalid value. Did you enter a number?") ;
}



Reply With Quote
Copyright Techfuels
Bookmarks