Input/Output with Scanner & printf
ইনপুট/আউটপুট — Scanner ও printf
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.
System.in দিয়ে input পড়া যায়, কিন্তু Scanner বা BufferedReader দিয়ে মোড়ালে সহজ হয়।
2. Reading with Scanner
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().
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);
}
}
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.
| Specifier | Meaning | Example |
|---|---|---|
%d | integer | %5d → width 5, right-aligned |
%f | floating point | %.2f → 2 decimal places |
%s | string | %-10s → left-aligned, width 10 |
%c | character | %c |
%b | boolean | %b → true/false |
%x / %o | hex / octal | %x → 2a |
%n | platform newline | safe alternative to \n |
%% | a literal % | 10%% → 10% |
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.
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);
}
}
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.
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
| Term | Meaning | বাংলায় |
|---|---|---|
| stdin / stdout / stderr | Standard input, output, error streams. | Java-র তিনটি standard stream। |
| Scanner | Convenience class for parsing typed input. | input parse করার সহজ class। |
| BufferedReader | Fast, line-based reader. | দ্রুত, লাইন-ভিত্তিক reader। |
| Format specifier | %d, %s, %f — placeholders in printf strings. | printf-এর placeholder। |
| %n | Platform-correct newline. | OS-অনুযায়ী newline। |
| Text block | Triple-quoted multi-line string (Java 15+). | তিন-quote multi-line string। |
8. Practice Problems
-
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.javaimport 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); } } -
Print a neat 3-column report (Name, Age, GPA) for 3 students using
printfalignment.তিনজন ছাত্রের Name, Age, GPA — aligned column-এ print করুন।✨ Show Answer (উত্তর দেখুন)
Main.javaclass 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]); } } -
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 nextnextLine()then sees that newline immediately and returns an empty string. The fix is to callsc.nextLine()once right afternextInt()to consume the leftover newline, or to read everything as lines and parse manually withInteger.parseInt. -
Read one line of space-separated integers from stdin and print their average to 3 decimals.এক লাইনে space-separated সংখ্যা পড়ে গড় ৩ দশমিকে।
✨ Show Answer (উত্তর দেখুন)
Main.javaimport 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); } } -
Use
String.formatto 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.javaclass 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.