Java user input
So far, what we have focused on has been one sided. That is, the programs just display some data and that's it, there is no interaction. But things are now going to get more interesting as we focus on accepting user input and interacting with the user based on that input.
This tutorial focuses on:
- User input package
- User input classes
- Handling the exceptions
User input package
The package that needs to be imported to accept user input is java.io. The java.io package contains classes and interfaces used for input and output.
The setup:import java.io.*;
class GetUserInput{
}
User input classes
To get user input, use the BufferedReader and InputStreamReader classes.
-
The InputStreamReader class - reads the user's input.
-
The BufferedReader class - buffers the user's input to make it work more efficiently.
Get some input:import java.io.*;
class GetUserInput{
public static void main(String[] args){
//the data that will be entered by the user
String name;
//an instance of the BufferedReader class
//will be used to read the data
BufferedReader reader;
//specify the reader variable
//to be a standard input buffer
reader = new BufferedReader(new InputStreamReader(System.in));
//ask the user for their name
System.out.print("What is your name? ");
//read the data entered by the user using
//the readLine() method of the BufferedReader class
//and store the value in the name variable
name = reader.readLine();
}
}
Handling the exceptions
Using the above code, you still cannot accept user input because one thing is still missing, and that is you have to catch the exception (a situation in which something unexpected might happen). The exception we will be working with in this situation is the IOException which is the exception used when an input error occurs. Exceptions are covered in detail in our java exceptions tutorial. For now, you should just know that exceptions are handled by executing a specific set of code if there is an error.
Get some input with exceptions:import java.io.*;
class GetUserInput{
public static void main(String[] args){
//the data that will be entered by the user
String name;
//an instance of the BufferedReader class
//will be used to read the data
BufferedReader reader;
//specify the reader variable
//to be a standard input buffer
reader = new BufferedReader(new InputStreamReader(System.in));
//ask the user for their name
System.out.print("What is your name? ");
try{
//read the data entered by the user using
//the readLine() method of the BufferedReader class
//and store the value in the name variable
name = reader.readLine();
//print the data entered by the user
System.out.println("Your name is " + name);
}
catch (IOException ioe){
//statement to execute if an input/output exception occurs
System.out.println("An unexpected error occured.");
}
}
}