RKTechGame | Scanner & PrintWriter (Deep Explained)

Scanner Class – User/Input Read karne ke Pro Tips!

Scanner class (java.util package) ka use ham mostly user se console input lene, ya file se data padhne ke liye karte hain. Ye kaafi flexible hai – alag alag data types ke liye instantly input read kar sakte ho!

Key Features

Common Use & Gotchas

Example 1: Console se input

import java.util.Scanner;
public class ScannerDemo {
  public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    System.out.print("Naam batao: ");
    String name = sc.nextLine();

    System.out.print("Umra batao: ");
    int age = sc.nextInt();

    System.out.println("Hello " + name + ", Age: " + age);
    sc.close();
  }
}

Example 2: File se input

Scanner sc = new Scanner(new File("data.txt"));
while(sc.hasNextLine()) {
  String line = sc.nextLine();
  System.out.println(line);
}
sc.close();

Advanced Tip

PrintWriter Class – Powerful Writing/Output!

PrintWriter class (java.io package) ka use text files, console ya network streams mein formatted data likhne ke liye hota hai. Ye FileWriter ya OutputStream se zyada flexible hai.

Key Features

Example 1: File Me Text Write Karna

import java.io.*;
public class PrintWriterDemo {
  public static void main(String[] args) {
    try {
      PrintWriter pw = new PrintWriter(new FileWriter("output.txt"));
      pw.println("Hello World!");
      pw.printf("Name: %s Age: %d", "Amit", 22);
      pw.close();
      System.out.println("File written!");
    } catch(Exception e) {
      e.printStackTrace();
    }
  }
}

Example 2: Direct Console Output

PrintWriter pw = new PrintWriter(System.out, true); // autoFlush on
pw.println("Yeh console par print hoga!");
pw.close();

Pro Tips & Limitations

Real-world Example: Scanner + PrintWriter Combo

Competitive programming ya exams mein aksar user input le ke file me likhna padta hai. Scanner se input lo, PrintWriter se save karo, super easy:

Scanner sc = new Scanner(System.in);
PrintWriter pw = new PrintWriter(new FileWriter("log.txt"));
while(sc.hasNextLine()) {
  String line = sc.nextLine();
  pw.println(line); // File me save
}
pw.close();
sc.close();