In Java, accepting user input is a fundamental part of many applications, especially interactive ones.
Java provides various ways to capture user input, with the most commonly used method being the Scanner class from the java.util package.
Other methods include using the BufferedReader class or working with graphical user interfaces (GUIs), but in this tutorial, we’ll focus on text-based input using Scanner.
In this tutorial, we'll cover:
Table of Contents
1. Introduction to the Scanner Class
The Scanner class in Java is used to capture input from various sources like input streams, files, or the console (keyboard). To use the Scanner class, you must import it from the java.util package.
Basic Syntax for Scanner:
import java.util.Scanner; public class InputExample { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); // Create a Scanner object System.out.println("Enter a string:"); String input = scanner.nextLine(); // Read user input System.out.println("You entered: " + input); } }
Explanation:
Scanner scanner = new Scanner(System.in);: Creates a Scanner object to read input from the console (System.in).
scanner.nextLine(): Reads a line of input from the user.
Always remember to close the Scanner after use to avoid resource leaks: scanner.close();.
2. Reading Different Types of Input
The Scanner class provides several methods to read different data types like strings, integers, floating-point numbers, etc.
Example 1: Reading a String
import java.util.Scanner; public class StringInputExample { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.println("Enter your name:"); String name = scanner.nextLine(); // Reading a string input System.out.println("Hello, " + name + "!"); scanner.close(); } }
Example 2: Reading an Integer
import java.util.Scanner; public class IntegerInputExample { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.println("Enter your age:"); int age = scanner.nextInt(); // Reading an integer input System.out.println("You are " + age + " years old."); scanner.close(); } }
Example 3: Reading a Double (Floating-point number)
import java.util.Scanner; public class DoubleInputExample { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.println("Enter your height (in meters):"); double height = scanner.nextDouble(); // Reading a double input System.out.println("Your height is " + height + " meters."); scanner.close(); } }
3. Handling Multiple Inputs
You can read multiple inputs of different types in sequence. For example, reading a name, age, and height from the user in one session.
Example 4: Reading Multiple Inputs
import java.util.Scanner; public class MultipleInputsExample { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.println("Enter your name:"); String name = scanner.nextLine(); // Reading a string System.out.println("Enter your age:"); int age = scanner.nextInt(); // Reading an integer System.out.println("Enter your height (in meters):"); double height = scanner.nextDouble(); // Reading a double System.out.println("Your name is " + name + ", you are " + age + " years old, and your height is " + height + " meters."); scanner.close(); } }
Explanation:
We used scanner.nextLine() to read a string, scanner.nextInt() to read an integer, and scanner.nextDouble() to read a floating-point number.
4. Handling Input Errors
When reading inputs, there is a possibility of the user entering invalid data (e.g., entering a string when an integer is expected). To handle such cases, you can use exception handling with try-catch blocks.
Example 5: Handling Input Mismatch Exception
import java.util.InputMismatchException; import java.util.Scanner; public class InputErrorHandlingExample { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); try { System.out.println("Enter your age:"); int age = scanner.nextInt(); // Expecting an integer System.out.println("You are " + age + " years old."); } catch (InputMismatchException e) { System.out.println("Invalid input! Please enter an integer."); } finally { scanner.close(); } } }
Explanation:
If the user enters a non-integer value when an integer is expected, the InputMismatchException is caught, and an error message is displayed.
The finally block ensures that the scanner is closed regardless of whether an exception occurred.
5. Alternative Methods of Input (BufferedReader)
While Scanner is the most commonly used method for reading user input, another alternative is BufferedReader. It is often used when performance is crucial (especially in reading large inputs), but it only reads input as strings, so you need to manually convert them to other types if necessary.
Example 6: Using BufferedReader
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class BufferedReaderExample { public static void main(String[] args) throws IOException { // Create a BufferedReader object BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); // Reading input as a string System.out.println("Enter your name:"); String name = reader.readLine(); // Converting string input to integer System.out.println("Enter your age:"); int age = Integer.parseInt(reader.readLine()); // Converting string to integer // Converting string input to double System.out.println("Enter your height:"); double height = Double.parseDouble(reader.readLine()); // Converting string to double System.out.println("Your name is " + name + ", you are " + age + " years old, and your height is " + height + " meters."); } }
Explanation:
BufferedReader reads input as a string using readLine().
We used Integer.parseInt() to convert the string input to an integer and Double.parseDouble() to convert the string input to a double.
6. Handling User Input with Prompts
Example 7: Asking for Confirmation
import java.util.Scanner; public class UserConfirmationExample { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.println("Do you want to continue? (yes/no)"); String response = scanner.nextLine(); if (response.equalsIgnoreCase("yes")) { System.out.println("Continuing..."); } else { System.out.println("Exiting..."); } scanner.close(); } }
Explanation:
equalsIgnoreCase() is used to compare strings without case sensitivity (e.g., “yes”, “YES”, “Yes” are all treated as equal).
7. Key Considerations
Closing Resources: Always remember to close your Scanner or BufferedReader to release the underlying resources after you're done reading input.
Handling Input Mismatches: Always anticipate possible input errors (like entering a string when an integer is expected) and handle them appropriately using exception handling techniques.
Input Parsing: When using BufferedReader, you need to manually parse strings into other data types like integers or doubles.
Conclusion
In this tutorial, we explored various ways of accepting user input in Java:
Using Scanner: The most commonly used method for reading different types of input from the console.
Handling multiple inputs: Reading and processing multiple types of input (strings, integers, floating-point numbers).
Handling input errors: Using exception handling to deal with invalid input.
Alternative input method (BufferedReader): Using BufferedReader for reading input as strings and converting to other types.
Confirmation prompts: Asking users for input confirmation.
Understanding how to capture and handle user input is essential in building interactive applications.