
Programs that only work with hardcoded values aren’t very useful. Real programs respond to users. They ask questions, accept answers, and adjust their behavior based on what you type.
Java’s Scanner class reads input from the keyboard. It’s the standard way to make interactive console programs.
Creating a Scanner
First, import the Scanner class. Then create a Scanner object connected to System.in, which represents keyboard input.
import java.util.Scanner;
public class InputExample {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Use scanner here
scanner.close();
}
}
The import statement goes at the top of your file, before the class declaration. Without it, Java doesn’t know what Scanner is.
Calling close() at the end releases resources. It’s good practice, though your program will still work if you forget.
Reading Strings
The nextLine() method reads an entire line of text, including spaces.
import java.util.Scanner;
public class NameGreeter {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("What is your name? ");
String name = scanner.nextLine();
System.out.println("Hello, " + name + "!");
scanner.close();
}
}
Run this program and it waits for you to type something and press Enter. Whatever you type becomes the value of name.
Note print() instead of println() for the prompt. This keeps the cursor on the same line as the question.
next() vs nextLine()
The next() method reads only until the first whitespace.
Scanner scanner = new Scanner(System.in);
System.out.print("Enter your full name: ");
String word = scanner.next();
System.out.println("You entered: " + word);
If you type “John Smith” and press Enter, word contains only “John”. The “Smith” stays in the input buffer.
Use nextLine() when you want the complete input. Use next() when you want single words.
Reading Numbers
Scanner has methods for reading different number types directly.
Scanner scanner = new Scanner(System.in);
System.out.print("Enter your age: ");
int age = scanner.nextInt();
System.out.print("Enter your height in meters: ");
double height = scanner.nextDouble();
System.out.println("Age: " + age + ", Height: " + height);
Available methods:
nextInt()– reads an intnextLong()– reads a longnextDouble()– reads a doublenextFloat()– reads a floatnextBoolean()– reads true or falsenextByte()– reads a bytenextShort()– reads a short
The nextLine() Problem
Mixing nextInt() or nextDouble() with nextLine() causes a common bug.
Scanner scanner = new Scanner(System.in);
System.out.print("Enter your age: ");
int age = scanner.nextInt();
System.out.print("Enter your name: ");
String name = scanner.nextLine();
System.out.println("Name: " + name + ", Age: " + age);
Run this and something strange happens. After you enter your age and press Enter, the program skips the name prompt entirely. The output shows an empty name.
The problem: nextInt() reads the number but leaves the newline character (from pressing Enter) in the buffer. When nextLine() runs, it immediately finds that newline and returns an empty string.
The fix: add an extra nextLine() to consume the leftover newline.
Scanner scanner = new Scanner(System.in);
System.out.print("Enter your age: ");
int age = scanner.nextInt();
scanner.nextLine(); // Consume the leftover newline
System.out.print("Enter your name: ");
String name = scanner.nextLine();
System.out.println("Name: " + name + ", Age: " + age);
This catches many beginners. Remember it when mixing number input with string input.
Input Validation
Users type unexpected things. If your program expects a number and receives “hello”, it crashes with an InputMismatchException.
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int num = scanner.nextInt(); // Crashes if user types "abc"
Using hasNextInt()
Scanner provides methods to check if the next input matches an expected type.
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
if (scanner.hasNextInt()) {
int num = scanner.nextInt();
System.out.println("You entered: " + num);
} else {
System.out.println("That's not a valid number");
scanner.next(); // Consume the invalid input
}
Available checking methods: hasNextInt(), hasNextDouble(), hasNextLine(), hasNext(), and others matching each read method.
Loop Until Valid
A common pattern keeps asking until the user provides valid input.
Scanner scanner = new Scanner(System.in);
int number;
while (true) {
System.out.print("Enter a positive number: ");
if (scanner.hasNextInt()) {
number = scanner.nextInt();
if (number > 0) {
break; // Valid input, exit loop
} else {
System.out.println("Number must be positive");
}
} else {
System.out.println("That's not a number");
scanner.next(); // Consume invalid input
}
}
System.out.println("You entered: " + number);
The loop continues until the user enters a valid positive integer.
Reading Multiple Values
You can read several values on one line.
Scanner scanner = new Scanner(System.in);
System.out.print("Enter three numbers separated by spaces: ");
int a = scanner.nextInt();
int b = scanner.nextInt();
int c = scanner.nextInt();
System.out.println("Sum: " + (a + b + c));
If the user types “10 20 30” and presses Enter, each nextInt() reads the next number.
Reading from Strings
Scanner can parse strings, not just keyboard input.
String data = "Alice 25 1.65";
Scanner scanner = new Scanner(data);
String name = scanner.next();
int age = scanner.nextInt();
double height = scanner.nextDouble();
System.out.println(name + " is " + age + " years old");
scanner.close();
This is useful for parsing formatted data or testing input handling without typing.
Practical Example: Simple Calculator
Here’s a calculator that reads two numbers and an operation:
import java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Simple Calculator");
System.out.println("-----------------");
System.out.print("Enter first number: ");
while (!scanner.hasNextDouble()) {
System.out.print("Invalid. Enter a number: ");
scanner.next();
}
double num1 = scanner.nextDouble();
System.out.print("Enter second number: ");
while (!scanner.hasNextDouble()) {
System.out.print("Invalid. Enter a number: ");
scanner.next();
}
double num2 = scanner.nextDouble();
scanner.nextLine(); // Consume newline
System.out.print("Enter operation (+, -, *, /): ");
String operation = scanner.nextLine().trim();
double result;
boolean valid = true;
switch (operation) {
case "+":
result = num1 + num2;
break;
case "-":
result = num1 - num2;
break;
case "*":
result = num1 * num2;
break;
case "/":
if (num2 == 0) {
System.out.println("Error: Cannot divide by zero");
valid = false;
result = 0;
} else {
result = num1 / num2;
}
break;
default:
System.out.println("Error: Unknown operation");
valid = false;
result = 0;
}
if (valid) {
System.out.println(num1 + " " + operation + " " + num2 + " = " + result);
}
scanner.close();
}
}
Sample run:
Simple Calculator
-----------------
Enter first number: 15
Enter second number: 4
Enter operation (+, -, *, /): *
15.0 * 4.0 = 60.0
Practical Example: Number Guessing Game
A game that combines loops, conditionals, and input:
import java.util.Scanner;
import java.util.Random;
public class GuessingGame {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Random random = new Random();
int secretNumber = random.nextInt(100) + 1; // 1 to 100
int attempts = 0;
int maxAttempts = 7;
boolean won = false;
System.out.println("I'm thinking of a number between 1 and 100.");
System.out.println("You have " + maxAttempts + " attempts.");
System.out.println();
while (attempts < maxAttempts) {
System.out.print("Guess #" + (attempts + 1) + ": ");
if (!scanner.hasNextInt()) {
System.out.println("Please enter a number.");
scanner.next();
continue;
}
int guess = scanner.nextInt();
attempts++;
if (guess < 1 || guess > 100) {
System.out.println("Guess must be between 1 and 100.");
continue;
}
if (guess == secretNumber) {
won = true;
break;
} else if (guess < secretNumber) {
System.out.println("Too low!");
} else {
System.out.println("Too high!");
}
int remaining = maxAttempts - attempts;
if (remaining > 0) {
System.out.println(remaining + " attempts remaining.");
}
System.out.println();
}
if (won) {
System.out.println("Congratulations! You got it in " + attempts + " attempts!");
} else {
System.out.println("Out of attempts! The number was " + secretNumber);
}
scanner.close();
}
}
Sample run:
I'm thinking of a number between 1 and 100.
You have 7 attempts.
Guess #1: 50
Too low!
6 attempts remaining.
Guess #2: 75
Too high!
5 attempts remaining.
Guess #3: 62
Too low!
4 attempts remaining.
Guess #4: 68
Congratulations! You got it in 4 attempts!
Common Mistakes
Forgetting to import Scanner. Add import java.util.Scanner; at the top of your file.
The nextLine() after nextInt() problem. Consume the leftover newline with an extra nextLine() call.
Not handling invalid input. Use hasNextInt() and similar methods to check before reading.
Creating multiple Scanners for System.in. Create one Scanner at the start and reuse it. Multiple Scanners on the same input stream cause problems.
// Wrong - creates Scanner inside loop
while (condition) {
Scanner scanner = new Scanner(System.in);
// ...
}
// Right - create once, reuse
Scanner scanner = new Scanner(System.in);
while (condition) {
// use scanner
}
Forgetting to consume invalid input. When hasNextInt() returns false, call next() to remove the invalid token before trying again.
What’s Next
You now have the tools to write interactive programs. The next phase covers methods, which let you organize code into reusable blocks, and arrays, which let you work with collections of data.
Related: Java Loops: for, while, do-while | Java Methods: Writing Reusable Code
Sources
- Oracle. “Scanner (Java SE 21).” Java Documentation. docs.oracle.com
- Oracle. “Scanning.” The Java Tutorials. docs.oracle.com


