Introduction To User Input
In real-world programs, interaction between the user and the computer is important. A program that shows only output without accepting input is one-sided. that’s the reason we use user input to take information from the user, process it, and then give results based on the output.
User input refers to the process of allowing a user to enter data while the program is running. This data can be a name, a number, an age, or any information that the program needs to work with easily.
In Java, user input is typically obtained from the keyboard, but it can also be sourced from files, databases, or other programs.
Why is User Input Important?
User input makes our programs dynamic and interactive, allowing them to work with real-time user data. For example:
- Asking the user for their name and displaying a personalized message.
- Taking the radius of a circle and calculating its area.
- Accepting numbers from the user and performing mathematical operations.
Without user input, programs would always produce the same result, no matter who runs them.
Methods for Taking User Input in Java
There are several ways to take input from users, but the Scanner class is the most beginner-friendly and commonly used method in Java.
It has other options available like BufferedReader and System.console(), but Scanner is preferred for simple console programs
How To Use Scanner Class in Java?
The Scanner class belongs to java.util package helps read data entered by the user from the keyboard.
It can read different types of data, such as strings, integers, floating-point numbers, and more.
Steps to Use Scanner
1) Import the Scanner class: First, we need to import it at the top of our Java file.
import java.util.Scanner;
2) Create a Scanner object:
Scanner scanner = new Scanner(System.in);
//Here, System.in means input is coming from the keyboard.
3) Read different types of input
- nextLine() → reads a full line of text
- nextInt() → reads an integer value
- nextDouble() → reads a decimal (floating-point) value
Example: Reading Basic User Input
This example shows how user input works using the Scanner class.
import java.util.Scanner;
public class UserInputExample {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in); // Create scanner object
System.out.print("Enter your favorite city: ");
String city = scanner.nextLine(); // Read string input
System.out.print("Enter the number of times you’ve visited it: ");
int visits = scanner.nextInt(); // Read integer input
System.out.print("Enter the average temperature there: ");
double temperature = scanner.nextDouble(); // Read double input
System.out.println("\n--- Travel Summary ---");
System.out.println("City: " + city);
System.out.println("Visits: " + visits + " times");
System.out.println("Average Temperature: " + temperature + "°C");
scanner.close(); // Close scanner to avoid memory leak
}
}
Output:
Enter your favorite city: Goa
Enter the number of times you’ve visited it: 3
Enter the average temperature there: 29.5
--- Travel Summary ---
City: Goa
Visits: 3 times
Average Temperature: 29.5°C
In this code:
- The Scanner class helps capture user input from the keyboard.
- Each method (nextLine, nextInt, nextDouble) is created to read a specific type of data.
- After using the Scanner, it’s good practice to close it using scanner.close() to free resources.
Common Methods of the Scanner Class
| Method | Description |
|---|---|
| nextInt() | Reads an integer value. |
| nextDouble() | Reads a double value. |
| nextFloat() | Reads a float value. |
| nextLine() | Reads an entire line of text. |
| next() | Reads a single word. |
| nextBoolean() | Reads a boolean value (true/false). |
| close() | Closes the scanner to free resources. |
Example: Reading Multiple Data Types
Sometimes, we need to take different types of inputs from the users, like their name, age, and height, and this can be easily done using the Scanner class.
It automatically converts the entered data into the correct type, such as String, int, or double.
Example code:
import java.util.Scanner;
public class MultiInputExample {
public static void main(String[] args) {
// Creating Scanner object to read input
Scanner input = new Scanner(System.in);
// Asking user for their details
System.out.print("Enter your name: ");
String name = input.nextLine();
System.out.print("Enter your age: ");
int age = input.nextInt();
System.out.print("Enter your height in centimeters: ");
double height = input.nextDouble();
// Displaying all collected information
System.out.println();
System.out.println("---- User Details ----");
System.out.println("Name : " + name);
System.out.println("Age : " + age);
System.out.println("Height : " + height + " cm");
// Closing Scanner object
input.close();
}
}
Output:
Enter your name: Riya
Enter your age: 24
Enter your height in centimeters: 162.7
---- User Details ----
Name : Riya
Age : 24
Height : 162.7 cm
Explanation of this code:
- Scanner input = new Scanner(System.in); creates a Scanner object to take input from the keyboard.
- nextLine() reads a line of text for strings.
- nextInt() reads an integer value for the numbers.
- nextDouble() reads a decimal value for the height.
- input.close() closes the scanner after use to prevent memory leaks.
Handling Input Errors in Java
When we take input data from the users, there’s always a chance that they entered invalid data, for example, typing letters when the program expects a number.
We can use error handling in Java with the help of the try-catch block.
Example: Handling Invalid User Input
import java.util.Scanner;
public class InputErrorHandling {
public static void main(String[] args) {
// Create a Scanner object to read input
Scanner scanner = new Scanner(System.in);
try {
System.out.print("Enter an integer number: ");
int number = scanner.nextInt(); // trying to read an integer value
System.out.println("You entered the number: " + number);
}
catch (Exception e) {
System.out.println("Oops! That’s not a valid number. Please enter an integer next time.");
}
// Always close scanner
scanner.close();
}
}
Output:
Enter an integer number: abc
Oops! That’s not a valid number. Please enter an integer next time.
How To Use BufferedReader in Java?
In Java, the BufferedReader class is another way to take input from users. It’s a bit more advanced than the Scanner class, but it is faster and more efficient, especially when handling large input data.
Example: Using BufferedReader to Read User Input
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
public class BufferedReaderExample {
public static void main(String[] args) throws IOException {
// Create a BufferedReader object that reads input from the console
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter your full name: ");
String name = reader.readLine(); // reads a line of text as a String
System.out.print("Enter your age: ");
int age = Integer.parseInt(reader.readLine()); // reads a line and converts it into integer
System.out.println("Welcome, " + name + "! You are " + age + " years old.");
}
}
Output:
Enter your full name: Mike
Enter your age: 20
Welcome, Mike! You are 20 years old.
- BufferReader is a special reader that takes input from the user and temporarily stores data before reading, and makes input faster.
- InputStreamReader(System.in) connects your keyboard input to the BufferedReader, allowing you to read from the console.
How To Use System.console() in Java?
In Java, the System.console() method provides another way to take input directly from the user.
It is mostly used in command-line or terminal-based programs rather than IDEs like Eclipse, IntelliJ, or NetBeans.
When you run your Java program from a terminal window (like Command Prompt or VS Code terminal), the console object can interact directly with the keyboard
Why Use System.console()?
- It works well in real command-line applications.
- It can hide sensitive input, such as passwords, from being displayed on the screen.
- It’s a lightweight and secure way to collect user input without additional classes like Scanner or BufferedReader.
Example: Using System.console()
public class ConsoleExample {
public static void main(String[] args) {
// Get the console object
java.io.Console console = System.console();
// Check if console is available
if (console != null) {
String name = console.readLine("Enter your name: ");
System.out.println("Hello, " + name + "! Welcome to Java input methods.");
} else {
System.out.println("Console not available. Please run this program in a terminal.");
}
}
}
Output:
Enter your name: Poll
Hello, Poll! Welcome to Java input methods.
How To Secure Password Input?
You can also take password input safely without showing characters on the screen:
char[] password = console.readPassword("Enter your password: ");
System.out.println("Password entered successfully!");
The password characters are hidden while typing. This is perfect for login systems.