Using Scanner class in Java - Time & Space Complexity
When we use the Scanner class to read input, it is important to understand how the time taken grows as the input size increases.
We want to know how the program's running time changes when we read more data.
Analyze the time complexity of the following code snippet.
import java.util.Scanner;
public class InputExample {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
for (int i = 0; i < n; i++) {
int value = scanner.nextInt();
System.out.println(value);
}
scanner.close();
}
}
This code reads an integer n, then reads n more integers and prints each one.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Reading an integer inside the loop using scanner.nextInt()
- How many times: Exactly n times, where n is the first input read
As the number n grows, the number of times we read input and print also grows linearly.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 reads and prints |
| 100 | About 100 reads and prints |
| 1000 | About 1000 reads and prints |
Pattern observation: The work grows directly in proportion to n; doubling n doubles the work.
Time Complexity: O(n)
This means the time taken grows in a straight line with the number of inputs read.
[X] Wrong: "Reading input with Scanner is always constant time regardless of input size."
[OK] Correct: Each call to scanner.nextInt() reads one integer, so more inputs mean more calls and more time.
Understanding how input reading scales helps you write efficient programs and shows you can think about performance in real situations.
"What if we changed the code to read all inputs into an array first, then process them? How would the time complexity change?"
Practice
Scanner class in Java?Solution
Step 1: Understand Scanner's role
The Scanner class is designed to read input from various sources, commonly from the user via the keyboard.Step 2: Differentiate from other classes
Writing output is done by System.out, GUI creation uses other libraries, and file handling uses classes like FileReader.Final Answer:
To read input from the user -> Option DQuick Check:
Scanner reads input = B [OK]
- Confusing Scanner with output classes
- Thinking Scanner creates GUI
- Assuming Scanner handles files only
Solution
Step 1: Identify correct Scanner constructor
The Scanner constructor requires an InputStream to read input. System.in is the standard input stream (keyboard).Step 2: Check other options
System.out and System.err are output streams, not input. System.in.read() returns an int, not an InputStream.Final Answer:
Scanner input = new Scanner(System.in); -> Option AQuick Check:
Use System.in for input Scanner [OK]
- Using System.out or System.err instead of System.in
- Passing System.in.read() which is an int, not InputStream
- Missing 'new' keyword
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int num = sc.nextInt();
System.out.println(num * 2);
sc.close();
}
}Solution
Step 1: Understand input reading
The program reads an integer from the user usingnextInt(). User inputs 25, so num = 25.Step 2: Calculate output
The program printsnum * 2, which is 25 * 2 = 50.Final Answer:
50 -> Option CQuick Check:
Input 25 * 2 = 50 [OK]
- Confusing input with output
- Forgetting to multiply by 2
- Not closing Scanner (though not causing output error)
import java.util.Scanner;
public class Demo {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter your name:");
String name = sc.nextInt();
System.out.println("Hello, " + name);
sc.close();
}
}Solution
Step 1: Check input method used
The code usesnextInt()to read the user's name, which is a String, not an integer.Step 2: Identify correct method
To read a String,nextLine()ornext()should be used instead ofnextInt().Final Answer:
Using nextInt() to read a String -> Option BQuick Check:
Use nextLine() for String input, not nextInt() [OK]
- Using nextInt() for String input
- Ignoring Scanner import
- Not closing Scanner (not error here)
- Misunderstanding print syntax
Scanner sc = new Scanner(System.in); int age = sc.nextInt(); // What next?
Solution
Step 1: Understand Scanner behavior after nextInt()
AfternextInt(), the newline character remains in the input buffer, so a directnextLine()reads that leftover newline.Step 2: Consume leftover newline before reading full line
Callingsc.nextLine()once consumes the leftover newline, then the nextnextLine()reads the actual full line input.Final Answer:
sc.nextLine(); String name = sc.nextLine(); -> Option AQuick Check:
Consume newline with nextLine() before reading full line [OK]
- Skipping the first nextLine() to consume newline
- Using next() which reads only one word
- Calling nextInt() again unnecessarily
Ready to prove it?
Pass the test and this pattern moves unknown
