Reading Input in Java
1. Reading Different Types (beginner)
One Scanner method per type. Trap: nextInt() leaves newline → next nextLine() reads empty! Fix: extra nextLine() after number.
2. Method Table (memorize!)
| To read | Method | Example input → value |
|---|---|---|
| int | nextInt() |
42 → 42 |
| double | nextDouble() |
3.14 → 3.14 |
| word | next() |
Asha Kumar → Asha (stops at space!) |
| full line | nextLine() |
Asha Kumar → full |
| char | next().charAt(0) |
A → 'A' |
| boolean | nextBoolean() |
true → true |
3. Code — Full Profile + Newline Trap Fix
Scanner sc = new Scanner(System.in);
System.out.print("age: ");
int age = sc.nextInt();
sc.nextLine(); // EAT leftover newline (critical!)
System.out.print("name: ");
String name = sc.nextLine(); // now reads full line correctly!
System.out.print("grade: ");
char g = sc.next().charAt(0);
System.out.printf("Hi %s, age %d, grade %c%n", name, age, g);
sc.close();
Without sc.nextLine() after nextInt(), name becomes "" (empty) — #1 input bug!
4. Validation (robust beginner)
if (sc.hasNextInt()) { int n = sc.nextInt(); }
else { System.out.println("numbers only!"); sc.next(); }
Wrong type → InputMismatchException (e.g. abc for nextInt()).
5. Exam Points
- Method table + newline-trap fix — 7 marks, very frequent.
- Full profile program — 5 marks, frequent.