Input/Output with Scanner & printf

ইনপুট/আউটপুট — Scanner ও printf

Read: ~25 min Beginner 5 practice problems Live code runner

1. The Three Streams

Every Java program has three standard streams: stdin (input), stdout (output), and stderr (errors). System.in, System.out, and System.err expose them. To read text from stdin, wrap System.in in a Scanner or BufferedReader. To write formatted text to stdout, use println or printf.

Java প্রোগ্রামে তিনটি standard stream — stdin (input), stdout (output), stderr (error)। System.in দিয়ে input পড়া যায়, কিন্তু Scanner বা BufferedReader দিয়ে মোড়ালে সহজ হয়।

2. Reading with Scanner

Main.java
import java.util.Scanner;

class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter name: ");
        String name = sc.nextLine();
        System.out.print("Enter age : ");
        int age = sc.nextInt();
        System.out.println("Hello " + name + ", age " + age);
        sc.close();
    }
}

Key methods:

  • next() — next whitespace-separated token.
  • nextLine() — the rest of the current line.
  • nextInt(), nextLong(), nextDouble(), nextBoolean() — typed reads.
  • hasNext(), hasNextInt() — check before reading.
Scanner-এর প্রধান method — token-এ token ভেঙে পড়ার জন্য next(), পুরো লাইনের জন্য nextLine(), সংখ্যার জন্য nextInt() ইত্যাদি। পড়ার আগে hasNext() দিয়ে চেক করা যায়।

3. The nextInt then nextLine Trap

nextInt() reads the integer but leaves the trailing newline in the buffer. The very next nextLine() will return that empty string immediately. Fix: always add an extra sc.nextLine() right after nextInt().

Main.java
import java.util.Scanner;

class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int age = sc.nextInt();
        sc.nextLine();                  // ← consume the leftover newline
        String fullName = sc.nextLine();
        System.out.println(age + " / " + fullName);
    }
}
Java-তে সবচেয়ে সাধারণ beginner bug — nextInt()-এর পর সরাসরি nextLine() দিলে খালি string ফেরে। সমাধান: মাঝে একবার sc.nextLine() বাড়তি ডাকুন।

4. printf — Formatted Output

System.out.printf(format, args...) follows the C-style format string convention, with Java-friendly %n for a platform-correct newline.

SpecifierMeaningExample
%dinteger%5d → width 5, right-aligned
%ffloating point%.2f → 2 decimal places
%sstring%-10s → left-aligned, width 10
%ccharacter%c
%bboolean%b → true/false
%x / %ohex / octal%x → 2a
%nplatform newlinesafe alternative to \n
%%a literal %10%% → 10%
Main.java
class Main {
    public static void main(String[] args) {
        String[] names = { "Arif", "Nilufar", "Shakib" };
        double[] gpa   = { 3.72, 3.91, 3.58 };

        System.out.printf("%-10s %6s%n", "Name", "GPA");
        System.out.printf("---------- ------%n");
        for (int i = 0; i < names.length; i++) {
            System.out.printf("%-10s %6.2f%n", names[i], gpa[i]);
        }

        // Number formatting examples
        System.out.printf("Tax: %d%%, total ৳%,.2f%n", 15, 12500.9);
        System.out.printf("Hex of 255 = %x%n", 255);
    }
}
printf দিয়ে সুন্দর column, দশমিক নিয়ন্ত্রণ, hex/oct ফরম্যাটে output করা যায়। %-10s বামে align, width 10। %,.2f হাজার-comma সহ ২ দশমিক। %% literal % প্রিন্ট করে।

5. BufferedReader — 10× Faster for Big Input

Scanner is convenient but slow. In competitive programming and large-input jobs, use BufferedReader instead — often an order of magnitude faster.

Main.java
import java.io.*;
import java.util.StringTokenizer;

class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int n = Integer.parseInt(br.readLine().trim());
        StringTokenizer st = new StringTokenizer(br.readLine());
        long sum = 0;
        for (int i = 0; i < n; i++) sum += Integer.parseInt(st.nextToken());
        System.out.println("Sum = " + sum);
    }
}
When to use which: Scanner for small, friendly, beginner code. BufferedReader + StringTokenizer when input size is measured in megabytes (LeetCode, Codeforces, large data jobs).
ছোট ইনপুটে Scanner যথেষ্ট। বড় ইনপুটে (competitive programming, log processing) BufferedReader + StringTokenizer ১০x দ্রুত।

6. String.format & Text Blocks

String.format uses the same format string as printf but returns a String instead of printing. Useful for logs, UI strings, and tests.

Main.java
class Main {
    public static void main(String[] args) {
        String msg = String.format("User %s has ৳%,.2f", "Arif", 12500.75);
        System.out.println(msg);

        // Java 15+ text block
        String json = """
                {
                  "name": "Arif",
                  "score": 92
                }""";
        System.out.println(json);
    }
}
String.format print করে না, ফর্ম্যাট করা String ফেরত দেয় — log, UI-তে দারুণ। Java 15+ থেকে triple-quoted """"..."""" text block দিয়ে সরাসরি JSON, SQL, HTML লেখা যায়।

7. Vocabulary

TermMeaningবাংলায়
stdin / stdout / stderrStandard input, output, error streams.Java-র তিনটি standard stream।
ScannerConvenience class for parsing typed input.input parse করার সহজ class।
BufferedReaderFast, line-based reader.দ্রুত, লাইন-ভিত্তিক reader।
Format specifier%d, %s, %f — placeholders in printf strings.printf-এর placeholder।
%nPlatform-correct newline.OS-অনুযায়ী newline।
Text blockTriple-quoted multi-line string (Java 15+).তিন-quote multi-line string।

8. Practice Problems

  1. Read two integers from stdin and print their sum, difference, product, and float division to 2 decimals.
    stdin থেকে দুটি integer পড়ে sum, difference, product, division প্রিন্ট করুন।
    ✨ Show Answer (উত্তর দেখুন)
    Main.java
    import java.util.Scanner;
    class Main {
        public static void main(String[] args) {
            Scanner sc = new Scanner(System.in);
            int a = sc.nextInt(), b = sc.nextInt();
            System.out.printf("sum  = %d%n", a + b);
            System.out.printf("diff = %d%n", a - b);
            System.out.printf("prod = %d%n", a * b);
            System.out.printf("div  = %.2f%n", (double) a / b);
        }
    }
  2. Print a neat 3-column report (Name, Age, GPA) for 3 students using printf alignment.
    তিনজন ছাত্রের Name, Age, GPA — aligned column-এ print করুন।
    ✨ Show Answer (উত্তর দেখুন)
    Main.java
    class Main {
        public static void main(String[] args) {
            String[] names = { "Arif", "Nila", "Rakib" };
            int[] ages     = { 21, 22, 20 };
            double[] gpa   = { 3.72, 3.91, 3.44 };
            System.out.printf("%-10s %4s %6s%n", "Name", "Age", "GPA");
            for (int i = 0; i < names.length; i++)
                System.out.printf("%-10s %4d %6.2f%n", names[i], ages[i], gpa[i]);
        }
    }
  3. Explain the "nextInt then nextLine" trap in 2-3 sentences and show the fix.
    nextInt-এর পর nextLine-এ কী সমস্যা হয়, সেটি ব্যাখ্যা ও fix দেখান।
    ✨ Show Answer (উত্তর দেখুন)

    Answer: nextInt() consumes only the digits and leaves the newline character in the input buffer. The next nextLine() then sees that newline immediately and returns an empty string. The fix is to call sc.nextLine() once right after nextInt() to consume the leftover newline, or to read everything as lines and parse manually with Integer.parseInt.

  4. Read one line of space-separated integers from stdin and print their average to 3 decimals.
    এক লাইনে space-separated সংখ্যা পড়ে গড় ৩ দশমিকে।
    ✨ Show Answer (উত্তর দেখুন)
    Main.java
    import java.io.*; import java.util.StringTokenizer;
    class Main {
        public static void main(String[] args) throws IOException {
            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
            StringTokenizer st = new StringTokenizer(br.readLine());
            long sum = 0; int count = 0;
            while (st.hasMoreTokens()) { sum += Integer.parseInt(st.nextToken()); count++; }
            System.out.printf("avg = %.3f%n", (double) sum / count);
        }
    }
  5. Use String.format to build a bKash-style receipt string with sender, receiver, amount, and save it in a variable, then print it.
    String.format দিয়ে bKash-style receipt string তৈরি ও print করুন।
    ✨ Show Answer (উত্তর দেখুন)
    Main.java
    class Main {
        public static void main(String[] args) {
            String r = String.format(
                "[bKash] %s → %s : ৳%,.2f (Ref %d)",
                "01712-000000", "01911-000000", 1250.50, 84321);
            System.out.println(r);
        }
    }

Summary — Module 08

Use Scanner for small, friendly inputs and remember to drain the newline after nextInt. Use BufferedReader + StringTokenizer when speed matters. Format output with printf using %d, %f, %s, width and precision. String.format returns a ready-to-log String. Text blocks make multi-line JSON and SQL finally pleasant in Java.

ছোট input-এ Scanner, বড় input-এ BufferedReader। printf দিয়ে সুন্দর formatted output। String.format log/UI-তে দারুণ। Java 15+ text block দিয়ে multi-line string সহজ।

Next Module → Control flow part I — if, else, and modern switch expressions.