Reading User Input
Read console input with `Scanner` and `nextLine()`, parse numbers from it, avoid the `nextInt()` trap and validate what the user types.
You are viewing a free preview lesson.
Lesson Overview
So far, most of the values in our programs have been written directly inside the source code. These are hard-coded values:
String studentName = "Sakib";
int age = 20;
A program like this gives the same result every time it runs. In an interactive program, the user provides data while the program is running: a name, an age, a mark, a course selection. In a console-based Java application, we use Scanner to read keyboard input. Input is also where programs meet text they did not expect, so we read it in one consistent way and start checking it.
Learning Objectives
After completing this lesson, you will be able to:
- Read user input from the console
- Import and create a
Scanner - Use
nextLine()to read a full line - Normalize String input
- Parse
intanddoublevalues from String input - Read multiple inputs sequentially
- Understand the problem that can occur when mixing
nextInt()andnextLine() - Perform basic input validation
- Write a simple interactive console program
What Is User Input?
User input is data provided by the user while a program is running:
Enter your name: Sakib
Enter your age: 20
Here, Sakib and 20 are values provided by the user. Instead of a hard-coded String name = "Sakib";, the program reads the value with a call such as String name = scanner.nextLine(); and can then store and process it.
What Is Scanner?
Scanner is a class from the Java standard library that helps read input. For keyboard input, we use Scanner with System.in, the standard input stream.
Importing Scanner
Scanner is a class from the java.util package, so write import java.util.Scanner; at the beginning of the source file. Basic structure:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
}
}
Creating a Scanner
To read keyboard input:
Scanner scanner = new Scanner(System.in);
Scanner— typescanner— variable namenew Scanner(...)— creates a Scanner objectSystem.in— keyboard input source
First Input Program
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = scanner.nextLine();
System.out.println("Hello, " + name);
scanner.close();
}
}
Possible interaction:
Enter your name: Sakib
Hello, Sakib
Displaying a Prompt
You should clearly tell the user what input is expected:
System.out.print("Enter your name: ");
print() does not create a new line, so the user types on the same line as the prompt:
Enter your name: Sakib
A clear prompt helps reduce invalid input. Enter your age in years: is better than a bare Input:.
Reading a Line with nextLine()
nextLine() reads an entire line, including spaces:
String value = scanner.nextLine();
If the user enters Md Samiul Alim Sakib, the stored value is Md Samiul Alim Sakib.
User input may also contain extra whitespace at the beginning or end. For text input, .strip() is often useful: with it, the input Sakib is stored as Sakib.
String name = scanner.nextLine().strip();
Reading Numeric Input
nextLine() always returns text. Suppose the user enters 20. We can first read it as a String and then parse it into an int:
String ageText = scanner.nextLine();
int age = Integer.parseInt(ageText.strip());
Usually, the two steps are written in one line:
System.out.print("Enter your age: ");
int age = Integer.parseInt(scanner.nextLine().strip());
System.out.println("Next year you will be " + (age + 1));
Interaction:
Enter your age: 20
Next year you will be 21
Decimal input works the same way with Double.parseDouble(). If the user enters 4990.50, the variable holds price = 4990.5.
System.out.print("Enter course price: ");
double price = Double.parseDouble(scanner.nextLine().strip());
Boolean Input
To parse true or false text:
System.out.print("Is enrollment open? ");
boolean enrollmentOpen =
Boolean.parseBoolean(scanner.nextLine().strip());
The input true gives the result true. However, yes is not considered true by Boolean.parseBoolean(). If you want user-friendly yes/no input, you can compare the String:
String answer = scanner.nextLine().strip();
boolean confirmed =
answer.equalsIgnoreCase("yes") || answer.equalsIgnoreCase("y");
Reading Multiple Inputs
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = scanner.nextLine().strip();
System.out.print("Enter your age: ");
int age = Integer.parseInt(scanner.nextLine().strip());
System.out.println();
System.out.println("Name: " + name);
System.out.println("Age: " + age);
scanner.close();
}
}
Possible interaction:
Enter your name: Sakib
Enter your age: 20
Name: Sakib
Age: 20
The nextInt() and nextLine() Problem
Scanner also provides methods for directly reading typed input:
nextInt()
nextDouble()
nextBoolean()
For example, int age = scanner.nextInt(); is valid. However, mixing these token-based methods with nextLine() can cause a common newline problem. Look at this code:
System.out.print("Enter your age: ");
int age = scanner.nextInt();
System.out.print("Enter your name: ");
String name = scanner.nextLine();
After the user enters their age and presses Enter, the name input appears to be skipped. For beginners, reading all input using nextLine() and parsing it afterward keeps the input flow more consistent.
Why Does the Input Get Skipped?
The user input is 20\n. nextInt() reads 20, but the newline \n produced by Enter remains in the input stream. The next call to scanner.nextLine() consumes that remaining newline and returns an empty String.
Fixing the Problem
One option is an extra nextLine() that consumes the leftover newline:
int age = scanner.nextInt();
scanner.nextLine();
String name = scanner.nextLine();
However, for beginner code, a more consistent approach is to read every input as a full line:
int age = Integer.parseInt(scanner.nextLine().strip());
Recommended Input Pattern
For simple console programs in this course, we will generally use this pattern:
String input = scanner.nextLine().strip();
Then use the text directly or parse it:
String name = input;
int age = Integer.parseInt(input);
double price = Double.parseDouble(input);
This approach consumes the full line (so no newline is left behind), lets us normalize whitespace, and keeps every input read the same way.
Validating Input
Invalid Numeric Input
Suppose the program parses the input as an integer:
int age = Integer.parseInt(scanner.nextLine());
If the user enters twenty, this is not valid integer text, and a NumberFormatException can occur at runtime.
Type Validity and Business Validity
An input is not necessarily valid just because it is a valid integer. For Age: -50, -50 is a valid integer, but it is not valid as an age. Suppose acceptable age is 0 to 150:
boolean validAge = age >= 0 && age <= 150;
Therefore, there can be two types of validation:
- Whether the input is of the expected type
- Whether the value is acceptable according to business rules
Blank Input
isBlank() is useful for checking required text input. If the user enters only spaces, missing is true:
String name = scanner.nextLine().strip();
boolean missing = name.isBlank();
Closing and Reusing the Scanner
After you finish reading input, call scanner.close();:
Scanner scanner = new Scanner(System.in);
// Read all input
scanner.close();
After a Scanner is closed, it cannot be used to read input again, so close it only after all input operations are complete.
Avoid creating several Scanners for the same System.in stream:
Scanner nameScanner = new Scanner(System.in);
Scanner ageScanner = new Scanner(System.in);
Generally, create one Scanner and reuse it:
Scanner scanner = new Scanner(System.in);
Complete Interactive Program
Now let's create a simple student result program.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter student name: ");
String studentName = scanner.nextLine().strip();
System.out.print("Enter mathematics mark: ");
int mathematicsMark = Integer.parseInt(scanner.nextLine().strip());
System.out.print("Enter English mark: ");
int englishMark = Integer.parseInt(scanner.nextLine().strip());
System.out.print("Enter science mark: ");
int scienceMark = Integer.parseInt(scanner.nextLine().strip());
int totalMarks = mathematicsMark + englishMark + scienceMark;
double averageMark = totalMarks / 3.0;
System.out.println();
System.out.println("Student: " + studentName);
System.out.println("Total: " + totalMarks);
System.out.println("Average: " + averageMark);
scanner.close();
}
}
Possible interaction:
Enter student name: Sakib
Enter mathematics mark: 80
Enter English mark: 90
Enter science mark: 85
Student: Sakib
Total: 255
Average: 85.0
Common Mistakes
Not Importing Scanner
Wrong:
Scanner scanner = new Scanner(System.in);
If there is no import, the compiler will not recognize Scanner. Add:
import java.util.Scanner;
Omitting new
Wrong:
Scanner scanner = Scanner(System.in);
Correct:
Scanner scanner = new Scanner(System.in);
Wrong Input Source
new Scanner(System.out) does not compile: System.out is where the program writes, not where it reads. Keyboard input comes from System.in.
Using next() for a Full Name
String name = scanner.next();
With the input Md Sakib, only Md will be read. For a full line, use scanner.nextLine();.
Practice Exercise 1: Name Input
Solutions: lesson 1.24.
Read the user's full name. For the input Md Samiul Alim Sakib, the output is:
Welcome, Md Samiul Alim Sakib
Practice Exercise 2: Age Input
Read the user's age. Expected interaction:
Enter your age: 20
Next year you will be 21
Practice Exercise 3: Numeric Parsing
Read all input using nextLine():
- Name
- Age
- Course price
Convert age to int and price to double.
Practice Exercise 4: Normalize Input
Using nextLine(), strip() and toLowerCase(), turn the input JAVA into java.
Practice Exercise 5: Yes or No
Prompt:
Do you want to continue? Enter yes or no:
Accept yes, y, YES and Y as positive values, and create a boolean shouldContinue.
Practice Exercise 6: Product Order
Read:
- Product name
- Unit price
- Quantity
Calculate subtotal = unit price × quantity, then print the product information and subtotal.
Practice Exercise 7: Student Result
Read from the user:
- Student name
- Mathematics mark
- English mark
- Science mark
Calculate the total and the decimal average.
Knowledge Check
Question 1
What is the standard stream for keyboard input?
Question 2
Which package contains Scanner?
Question 3
What is the import statement for Scanner?
Question 4
How do you create a Scanner for keyboard input?
Question 5
Which method reads a full line?
Question 6
What can be used to remove surrounding whitespace from input?
Question 7
Which method converts String input to an int?
Question 8
Which method converts String input to a double?
Question 9
Why can nextLine() appear to be skipped after nextInt()?
Question 10
What is the recommended input strategy for beginner console programs in this course?
Question 11
What can happen when invalid numeric text is parsed?
Question 12
Is type-valid input always business-valid?
Question 13
When should a Scanner be closed?
Question 14
Should multiple Scanner instances generally be created for the same System.in?
Knowledge Check Answers
Answer 1
System.in
Answer 2
java.util
Answer 3
import java.util.Scanner;
Answer 4
Scanner scanner = new Scanner(System.in);
Answer 5
nextLine()
Answer 6
strip()
Answer 7
Integer.parseInt()
Answer 8
Double.parseDouble()
Answer 9
nextInt() reads the numeric token but leaves the newline from pressing Enter in the input stream. The next nextLine() consumes that newline and returns an empty String.
Answer 10
Read all input using nextLine(), normalize it with .strip() when needed, and convert numeric values using parsing methods.
Answer 11
A NumberFormatException can occur.
Answer 12
No. For example, 500 is a valid integer but may be invalid as an age or exam mark.
Answer 13
After all input operations are complete.
Answer 14
Generally, no. It is better to create one Scanner and reuse it.
Lesson Summary
Scannerfromjava.utilreads keyboard input fromSystem.in.- Show a clear prompt with
System.out.print()before reading a value. nextLine()reads a full line, including spaces, and always returns text.- Normalize text input with
.strip(), then parse numbers withInteger.parseInt()orDouble.parseDouble(). - Mixing
nextInt()withnextLine()leaves a newline behind, so in this course you read every input as a full line. - Invalid numeric text causes a
NumberFormatException, and a valid number can still break a business rule. - Create one Scanner, reuse it, and close it only after all input has been read.
Think first
Coming soonCheckpoint questions that ask you to commit to an answer before the lesson shows it.