
Scanner Class
Class in Java Definition The Scanner class is a predefined class in Java used to take input from the user. It belongs to: java.util package Why Scanner? It is used to read: int double float String boolean long etc. How to Use Scanner Step 1: Import the package import java.util.Scanner; Step 2: Create Scanner Object Scanner sc = new Scanner(System.in); ✔ System.in → Takes input from keyboard ✔ sc → Object name Step 3: Take Input int age = sc.nextInt(); String name = sc.nextLine(); double salary = sc.nextDouble(); Important Concept (Very Important 🔥) If you write: int age = sc.nextInt(); String name = sc.nextLine(); The nextLine() may get skipped because nextInt() does not consume the newline. ✔ Correct way: int age = sc.nextInt(); sc.nextLine(); // consume leftover newline String name = sc.nextLine(); Common Scanner Methods nextInt()-Integer nextDouble() - Decimal number next() - Single word nextLine() - Full sentence nextBoolean() - true/false Always Close Scanner Java Copy code sc.clo
Continue reading on Dev.to Beginners
Opens in a new tab




