Back to Java
2025-12-295 min read

Java User Input

Learn Java User Input step by step with clear examples and exercises.

Why This Matters

Understanding how to take user input in Java using the Scanner class is crucial for building interactive applications that can gather user data dynamically. By mastering this skill, you will be better equipped to create engaging programs, prepare for coding interviews, and tackle real-world programming tasks more effectively.

In addition, learning about user input helps you understand the fundamental concept of interacting with users in a programming context, which is essential for developing applications that cater to user needs and preferences.

Prerequisites

Before diving into Java User Input, it's essential to have a strong foundation in the following topics:

  1. Basic Java syntax (variables, operators, control structures)
  2. Understanding classes and objects in Java
  3. Exception handling in Java (try-catch blocks)
  4. Familiarity with the String class and string manipulation techniques
  5. Knowledge of basic data types such as int, double, boolean, etc.
  6. Comfortable using integrated development environments (IDEs) like Eclipse or IntelliJ IDEA
  7. Understanding of Java packages and importing classes

Core Concept

The Scanner class in Java allows users to input data through the keyboard. To use it, you first need to import the Scanner class:

import java.util.Scanner;

Next, create a Scanner object and initialize it with System.in, which represents the standard input stream:

Scanner scanner = new Scanner(System.in);

Now that you have a Scanner object, you can use various methods to read user input. Here's an example of reading a single line of text using the nextLine() method:

String userInput = scanner.nextLine();
System.out.println("You entered: " + userInput);

To read individual words or numbers, use the next(), nextInt(), nextDouble(), and other methods provided by the Scanner class. For example, to read an integer:

int number = scanner.nextInt();
System.out.println("You entered the number: " + number);

Remember to always close the Scanner object once you're done using it to free up system resources:

scanner.close();

Reading User Input in a Loop

When reading user input in a loop, it's important to check if there's more input available before reading it:

while (scanner.hasNext()) {
String input = scanner.nextLine();
// process the input here
}

Handling Special Cases

In some cases, you may encounter special characters or situations that require additional handling. For example, when reading a line of text with the nextLine() method, it's common to encounter an extra newline character at the end of the input. To handle this, you can use the following code:

String userInput = scanner.nextLine().trim();

Reading User Input from Multiple Sources

The Scanner class allows you to read input from various sources, not just the keyboard. You can create a Scanner object and initialize it with a FileInputStream, String, or even another Scanner. This opens up possibilities for reading data from files, strings, or even other programs.

Worked Example

Let's create a simple Java program that takes user input and calculates the sum of two numbers. We will also demonstrate reading user input in a loop to continue taking input until the user decides to stop.

import java.util.Scanner;

public class UserInputExample {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

int total = 0;
System.out.println("Enter numbers (type 'quit' to stop):");

while (scanner.hasNext()) {
String input = scanner.nextLine();
if ("quit".equalsIgnoreCase(input)) {
break;
}

try {
int number = Integer.parseInt(input);
total += number;
System.out.println("Added: " + number);
} catch (NumberFormatException e) {
System.err.println("Invalid input: " + input);
}
}

System.out.printf("The total is: %d\n", total);
scanner.close();
}
}

Common Mistakes

1. Forgetting to import the Scanner class

Always start by importing java.util.Scanner.

2. Not closing the Scanner object

Remember to close the Scanner object after using it to free up system resources.

3. Reading user input in a loop without checking for input end

When reading user input in a loop, always check if there's more input available before reading it:

while (scanner.hasNext()) {
String input = scanner.nextLine();
// process the input here
}

4. Ignoring special cases when reading user input

Always handle special characters or situations that may arise when reading user input, such as an extra newline character at the end of the input.

5. Not handling invalid input correctly

When reading user input, it's important to validate and handle exceptions appropriately to ensure your program can continue running smoothly.

Practice Questions

  1. Write a program that takes three numbers as user input and calculates their average.
  2. Create a program that reads a line of text from the user, converts it to uppercase, and prints the result.
  3. Write a program that prompts the user to enter a password and checks if it meets the following conditions:
  • At least one digit
  • At least one lowercase letter
  • At least one uppercase letter
  • Length between 8 and 16 characters
  1. Write a program that takes a list of integers as user input (separated by commas) and calculates their sum.
  2. Create a program that reads a line of text from the user, removes all duplicate words, and prints the result.
  3. Write a program that takes user input for two numbers, performs arithmetic operations (+, -, *, /), and displays the results.
  4. Write a program that reads a file containing integers (one per line) and calculates their sum.
  5. Create a program that reads a list of strings from the user (separated by commas), removes duplicates, sorts them alphabetically, and prints the result.
  6. Write a program that takes user input for a person's name and age, then greets them with a personalized message.
  7. Create a program that reads a list of strings from the user (separated by commas), removes duplicates, sorts them alphabetically, and prints the result while also counting the occurrence of each word.

FAQ

Q: What happens if I don't close the Scanner object?

A: Leaving the Scanner open can cause issues with your program, as it consumes system resources. It's always best to close the Scanner once you're done using it.

Q: Can I use the Scanner class for reading files instead of user input?

A: Yes! You can create a Scanner object and initialize it with a FileInputStream to read from a file. However, this is beyond the scope of this lesson.

Q: Are there any limitations on the types of data I can read using the Scanner class?

A: The Scanner class supports various primitive data types (int, double, boolean, etc.) as well as strings and tokens. For more complex data structures like arrays or lists, you may need to use other methods or libraries.

Q: How can I read input from a specific file using the Scanner class?

A: To read input from a specific file, create a Scanner object and initialize it with a FileInputStream. Here's an example:

import java.io.File;
import java.io.FileInputStream;
import java.util.Scanner;

public class FileReaderExample {
public static void main(String[] args) throws Exception {
Scanner scanner = new Scanner(new FileInputStream(new File("input.txt")));

while (scanner.hasNextLine()) {
String line = scanner.nextLine();
System.out.println(line);
}

scanner.close();
}
}
Java User Input | Java | XQA Learn