Foundation

09 — User Input

Previous: 08 Strings · Next: 10 Classes & Objects

▶️ java pkg1core/core24UserInput.java


Scanner — easiest for beginners

java
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

java
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:

code
11. Ask user name and age (Scanner)22. Validate age > 0 (if/else)33. Store scores in an array44. Print average with formatted String

Practice

  1. Run core24UserInput (uses simulated input — read the code).
  2. Uncomment the interactive section and try with real keyboard input.
  3. Build the mini project above.

Milestone: You completed Java Basics (chapters 01–09). 🎉

Next → 10 Classes & Objects Related → 01 Core Java