Accepting Input from the Keyboard
1. Big Picture (beginner)
Java reads keyboard via stream: System.in (bytes) → wrapper (Scanner easiest, BufferedReader fastest) → your variables. Exams expect Scanner (simple) + know alternatives exist.
2. Three Ways (exam table)
| Way | Code hint | Beginner verdict |
|---|---|---|
Scanner (easiest) |
new Scanner(System.in) |
USE THIS (all examples here) |
BufferedReader |
new BufferedReader(new InputStreamReader(System.in)) |
fast, but readLine + parse + throws |
Console / args |
System.console(), args[0] |
special cases (passwords, CLI) |
3. Minimal Pattern (memorize!)
import java.util.Scanner;
public class Input {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in); // connect keyboard
System.out.print("Enter age: ");
int age = sc.nextInt(); // read
System.out.println("next year: " + (age + 1));
sc.close(); // free keyboard
}
}
4. Golden Rules
import java.util.Scanner;at top (else ERROR).- Prompt BEFORE read (
print, notprintln— cursor stays!). close()once at end. OneScannerper program (don't make two onSystem.in!).
5. Exam Points
- Three ways + Scanner program — 5 marks, very frequent.
- Import + close rules — 2-3 marks, frequent.