Foundation
09 — User Input
Previous: 08 Strings · Next: 10 Classes & Objects
▶️ java pkg1core/core24UserInput.java
Scanner — easiest for beginners
1Scanner sc = new Scanner(System.in);2System.out.print("Name: ");3String name = sc.nextLine();4 5System.out.print("Age: ");6int age = sc.nextInt();7sc.nextLine(); // consume leftover newline — IMPORTANT!| Method | Reads |
|---|---|
nextLine() |
Entire line as String |
nextInt() |
Next int token |
nextDouble() |
Next double |
hasNext() |
More input available? |
⚠️ Classic bug: nextInt() then nextLine() — the nextLine() reads an empty string because the newline after the number is still in the buffer. Call nextLine() once to consume it.
BufferedReader — faster for large text
1BufferedReader br = new BufferedReader(new InputStreamReader(System.in));2String line = br.readLine();Preferred for reading many lines from files or stdin in production.
Mini project idea
Combine everything from Part 1:
11. Ask user name and age (Scanner)22. Validate age > 0 (if/else)33. Store scores in an array44. Print average with formatted StringPractice
- Run
core24UserInput(uses simulated input — read the code). - Uncomment the interactive section and try with real keyboard input.
- Build the mini project above.
Milestone: You completed Java Basics (chapters 01–09). 🎉
Next → 10 Classes & Objects Related → 01 Core Java
Source named in this chapter
- core24UserInputpkg1core/core24UserInput.java