Core Java
core24UserInput
- Path
- pkg1core/core24UserInput.java
- Package
- pkg1core
- Study order
- 9
- Run
- Single-file source launch
- Command
- java pkg1core/core24UserInput.java
- Lesson
- Back to the chapter
There is no in-browser runner. This is the file from the curriculum, unchanged.
1package pkg1core;2 3/*4 * core24UserInput.java5 * ----------------6 * Reading user input with Scanner and BufferedReader.7 *8 * EXPLANATION:9 * - Scanner: easy token-based parsing (nextInt, nextLine). Good for learning.10 * - BufferedReader + InputStreamReader: faster for large text; readLine() per line.11 * - Pitfall: mixing nextInt() then nextLine() without consuming the leftover newline.12 */13import java.io.BufferedReader;14import java.io.InputStreamReader;15import java.util.Scanner;16 17public class core24UserInput {18 19 static void demoScanner() {20 // Simulated input via String — same API as System.in21 Scanner sc = new Scanner("Alice\n25\n3.14\n");22 System.out.println("Scanner demo:");23 System.out.println(" name: " + sc.nextLine());24 System.out.println(" age: " + sc.nextInt());25 sc.nextLine(); // consume newline after nextInt before next nextLine26 sc.close();27 }28 29 static void demoBufferedReader() throws Exception {30 String simulated = "line one\nline two\n";31 BufferedReader br = new BufferedReader(new InputStreamReader(32 new java.io.ByteArrayInputStream(simulated.getBytes())));33 System.out.println("BufferedReader demo:");34 System.out.println(" " + br.readLine());35 System.out.println(" " + br.readLine());36 br.close();37 }38 39 public static void main(String[] args) throws Exception {40 demoScanner();41 demoBufferedReader();42 43 // Real interactive use (uncomment to try):44 // Scanner in = new Scanner(System.in);45 // System.out.print("Enter your name: ");46 // String name = in.nextLine();47 // System.out.println("Hello, " + name);48 }49}