There are many ways to get information from the user. In many cases, the user must be told that they should enter some information. This is known as prompting the user. A user prompt is a line of text that is output to the user that explains what information they should input next. We can prompt the user by displaying information in a dialog box, a program frame or even the console window. All programs that require the user to input information while the program is running, must prompt the user for that information in some manner.
When a program is waiting for input at the console, there is sometimes a blinking cursor in the console window indicating that the user should type some information. But, this is not always the case. The user will only know what information to type, if the program describes that information in the form of a user prompt. (See Console Output for more information on user prompts.)
The use of several of the Java I/O classes are required to successfully receive input that is typed by the user. The java.io package contains most, if not all, of the classes you will need to use. Don't worry, you won't need to use all 50+ classes. But, you will need to learn about and use at least three of them. All three classes are in the java.io package. Either use the fully qualified name shown or import the java.io package.
Steps for console based user input:
1. Use the System.in object to create an InputStreamReader object.
2. Use the InputStreamReader object to create a BufferedReader object.
3. Display a prompt to the user for the desired data.
4. Use the BufferedReader object to read a line of text from the user.
5. Do something interesting with the input received from the user.
ex-
// 1. Create an InputStreamReader using the standard input stream.
InputStreamReader isr = new InputStreamReader( System.in );
// 2. Create a BufferedReader using the InputStreamReader created.
BufferedReader stdin = new BufferedReader( isr );
// 3. Don't forget to prompt the user
System.out.print( "Type some data for the program: " );
// 4. Use the BufferedReader to read a line of text from the user.
String input = stdin.readLine();
// 5. Now, you can do anything with the input string that you need to.
// Like, output it to the user.
System.out.println( "input = " + input );
Answered by
Nagendra
, an ibibo Master,
at
7:23 PM on July 11, 2008