Programming and Java Fundamentals

Reading User Input

ReadingPreview

You are viewing a free preview lesson.

Lesson Overview

এখন পর্যন্ত আমাদের Java program-এর value source code-এর মধ্যে সরাসরি লেখা ছিল।

Example:

String studentName = "Sakib";
int age = 20;
double coursePrice = 4990.50;

এগুলোকে hard-coded value বলা যায়।

কিন্তু real application-এ program-কে user-এর কাছ থেকে data নিতে হয়।

উদাহরণ:

  • User-এর নাম
  • বয়স
  • Email address
  • Product quantity
  • Exam mark
  • Course selection
  • Login information
  • Search text

Console-based Java application-এ keyboard input নেওয়ার জন্য commonly Scanner class ব্যবহার করা হয়।

এই lesson-এ আমরা শিখব:

  • User input কী
  • Scanner কী
  • Scanner import করা
  • Keyboard input পড়া
  • Prompt দেখানো
  • nextLine()
  • nextInt()
  • nextDouble()
  • nextBoolean()
  • Multiple input নেওয়া
  • nextInt() এবং nextLine() problem
  • String input parse করা
  • Invalid input detect করা
  • Scanner close করা
  • একটি interactive console application তৈরি করা

Learning Objectives

এই lesson শেষ করার পর আপনি পারবেন:

  • Console input কী, তা ব্যাখ্যা করতে
  • Scanner class import করতে
  • Keyboard input-এর জন্য Scanner object তৈরি করতে
  • Text, integer, decimal এবং boolean input পড়তে
  • User-friendly prompt দেখাতে
  • Multiple input sequentially নিতে
  • next() এবং nextLine()-এর পার্থক্য বুঝতে
  • nextInt()-এর পরে nextLine() problem explain করতে
  • String input parse করে numeric value তৈরি করতে
  • Input normalize করতে
  • hasNextInt() এবং hasNextDouble() ব্যবহার করতে
  • Invalid input-এর basic handling করতে
  • Scanner resource close করার rule বুঝতে
  • Complete interactive console program লিখতে

What Is User Input?

User input হলো program চলার সময় user-এর দেওয়া data।

Example interaction:

Enter your name: Sakib
Enter your age: 20

এখানে:

Sakib

এবং:

20

User input।

Program এই value store, validate এবং process করতে পারে।


Hard-Coded Value vs User Input

Hard-Coded Value

String name = "Sakib";

Value source code-এর মধ্যে fixed।

Program run করার পর user এটি পরিবর্তন করতে পারে না।


User Input

String name = scanner.nextLine();

Program run করার সময় user value দেয়।

Different user different input দিতে পারে।


Why Do Programs Need User Input?

User input program-কে interactive করে।

Input ব্যবহার করে program:

  • User-specific result তৈরি করতে পারে
  • Calculation করতে পারে
  • Decision নিতে পারে
  • Search করতে পারে
  • Form data collect করতে পারে
  • Configuration নিতে পারে
  • User command process করতে পারে

Example:

Enter first number: 10
Enter second number: 20
Total: 30

Standard Input

Console application-এ keyboard input সাধারণত standard input stream-এর মাধ্যমে আসে।

Java-তে standard input:

System.in

আমরা System.in directly ব্যবহার না করে Scanner class ব্যবহার করব।


What Is Scanner?

Scanner Java standard library-এর একটি class।

এটি text input read এবং parse করতে সাহায্য করে।

Scanner ব্যবহার করে পড়া যায়:

  • String
  • Integer
  • Long
  • Float
  • Double
  • Boolean
  • Other token-based values

Importing Scanner

Scanner java.util package-এর অংশ।

Source file-এর শুরুতে import করতে হবে:

import java.util.Scanner;

Complete structure:

import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
    }
}

Why Is Import Required?

Scanner java.lang package-এর অংশ নয়।

Java automatically java.lang import করে।

এই কারণে নিচের classগুলো direct ব্যবহার করা যায়:

String
System
Math
Integer
Double

কিন্তু Scanner ব্যবহার করতে সাধারণত explicit import প্রয়োজন:

import java.util.Scanner;

Creating a Scanner Object

Keyboard input পড়ার জন্য:

Scanner scanner =
        new Scanner(System.in);

এখানে:

  • Scanner variable type
  • scanner variable name
  • new Scanner(...) object creation
  • System.in input source

Complete Basic Scanner Program

import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        Scanner scanner =
                new Scanner(System.in);

        System.out.print(
                "Enter your name: "
        );

        String name =
                scanner.nextLine();

        System.out.println(
                "Hello, " + name
        );

        scanner.close();
    }
}

Possible interaction:

Enter your name: Sakib
Hello, Sakib

Showing a Prompt

User-কে কী input দিতে হবে, তা বোঝাতে prompt দেখানো উচিত।

System.out.print(
        "Enter your name: "
);

print() new line তৈরি করে না।

তাই user একই line-এ input দিতে পারে:

Enter your name: Sakib

Using println() for Prompt

System.out.println(
        "Enter your name:"
);

Interaction:

Enter your name:
Sakib

দুটিই valid।

Console form-এর জন্য print() অনেক সময় বেশি natural।


Reading a Full Line with nextLine()

String name =
        scanner.nextLine();

nextLine() user-এর complete line পড়ে।

Input:

Md Samiul Alim Sakib

Stored value:

Md Samiul Alim Sakib

Spacesসহ পুরো line পাওয়া যায়।


Example: Reading a Name

import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        Scanner scanner =
                new Scanner(System.in);

        System.out.print(
                "Enter your full name: "
        );

        String fullName =
                scanner.nextLine();

        System.out.println(
                "Welcome, " + fullName
        );

        scanner.close();
    }
}

Reading a Single Token with next()

String name =
        scanner.next();

next() whitespace পর্যন্ত একটি token পড়ে।

Input:

Md Samiul Alim Sakib

Stored value:

Md

কারণ প্রথম space-এ token শেষ হয়েছে।


next() vs nextLine()

Methodকী পড়ে
next()পরবর্তী token
nextLine()পুরো line

Example Input

Java and OOP Foundation

Using:

scanner.next()

Result:

Java

Using:

scanner.nextLine()

Result:

Java and OOP Foundation

Text input-এর জন্য সাধারণত nextLine() বেশি useful।


Reading an Integer with nextInt()

int age =
        scanner.nextInt();

Complete example:

import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        Scanner scanner =
                new Scanner(System.in);

        System.out.print(
                "Enter your age: "
        );

        int age =
                scanner.nextInt();

        System.out.println(
                "Your age is " + age
        );

        scanner.close();
    }
}

Interaction:

Enter your age: 20
Your age is 20

Reading a long

long population =
        scanner.nextLong();

Example input:

8000000000

Reading a Decimal with nextDouble()

double price =
        scanner.nextDouble();

Example:

import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        Scanner scanner =
                new Scanner(System.in);

        System.out.print(
                "Enter course price: "
        );

        double price =
                scanner.nextDouble();

        System.out.println(
                "Course price: " + price
        );

        scanner.close();
    }
}

Input:

4990.50

Output:

Course price: 4990.5

Reading a float

float temperature =
        scanner.nextFloat();

Input:

36.5

No F suffix is typed by user।

F suffix source-code literal-এর জন্য, console input-এর জন্য নয়।


Reading a Boolean

boolean active =
        scanner.nextBoolean();

Accepted text commonly:

true
false

Case-insensitive variations কাজ করতে পারে:

TRUE
False

Example:

System.out.print(
        "Is the course available? "
);

boolean available =
        scanner.nextBoolean();

User Cannot Enter yes for nextBoolean()

Input:

yes

nextBoolean() এটি valid boolean হিসেবে accept করবে না।

Expected:

true

অথবা:

false

User-friendly program-এ "yes" এবং "no" manually parse করা যায়।


Reading Multiple Inputs

import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        Scanner scanner =
                new Scanner(System.in);

        System.out.print(
                "Enter your name: "
        );

        String name =
                scanner.nextLine();

        System.out.print(
                "Enter your age: "
        );

        int age =
                scanner.nextInt();

        System.out.println(
                "Name: " + name
        );

        System.out.println(
                "Age: " + age
        );

        scanner.close();
    }
}

Possible interaction:

Enter your name: Sakib
Enter your age: 20
Name: Sakib
Age: 20

The nextInt() and nextLine() Problem

এটি beginnerদের সবচেয়ে common Scanner problemগুলোর একটি।

Code:

System.out.print(
        "Enter your age: "
);

int age =
        scanner.nextInt();

System.out.print(
        "Enter your full name: "
);

String fullName =
        scanner.nextLine();

User age input দেওয়ার পর program name input skip করতে পারে।


Why Does nextLine() Get Skipped?

Input:

20\n

এখানে:

20

integer token।

\n

Enter press করার কারণে newline।

nextInt() শুধু integer token পড়ে:

20

কিন্তু newline input buffer-এ রেখে দেয়।

পরবর্তী:

scanner.nextLine()

remaining newline পড়ে এবং empty String return করে।


Fixing the Skipped nextLine()

nextInt()-এর পরে extra nextLine() call করুন।

int age =
        scanner.nextInt();

scanner.nextLine();

String fullName =
        scanner.nextLine();

Extra nextLine() leftover newline consume করে।


Complete Fixed Example

import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        Scanner scanner =
                new Scanner(System.in);

        System.out.print(
                "Enter your age: "
        );

        int age =
                scanner.nextInt();

        scanner.nextLine();

        System.out.print(
                "Enter your full name: "
        );

        String fullName =
                scanner.nextLine();

        System.out.println(
                "Name: " + fullName
        );

        System.out.println(
                "Age: " + age
        );

        scanner.close();
    }
}

The Same Problem with Other Token Methods

এই issue শুধু nextInt() নয়।

Token-based methods:

next()
nextInt()
nextLong()
nextDouble()
nextFloat()
nextBoolean()

এগুলো line ending consume নাও করতে পারে।

পরবর্তী nextLine() call করলে leftover newline পাওয়া যেতে পারে।


A Simpler Input Strategy

একটি simple এবং consistent approach হলো:

সব input nextLine() দিয়ে পড়ুন, তারপর প্রয়োজন অনুযায়ী parse করুন।

Example:

System.out.print(
        "Enter your age: "
);

String ageText =
        scanner.nextLine();

int age =
        Integer.parseInt(
                ageText
        );

এই approach nextInt() এবং nextLine() mixing problem কমায়।


Reading Integer Through nextLine()

System.out.print(
        "Enter your age: "
);

String ageText =
        scanner.nextLine();

int age =
        Integer.parseInt(
                ageText.strip()
        );

Benefits:

  • Full line consume হয়
  • Leading/trailing whitespace remove করা যায়
  • Validation control সহজ
  • Input flow consistent থাকে

Reading Decimal Through nextLine()

System.out.print(
        "Enter course price: "
);

String priceText =
        scanner.nextLine();

double price =
        Double.parseDouble(
                priceText.strip()
        );

Reading Boolean Through nextLine()

System.out.print(
        "Is the course available? "
);

String availableText =
        scanner.nextLine();

boolean available =
        Boolean.parseBoolean(
                availableText.strip()
        );

তবে "yes" input false হবে।

Custom handling প্রয়োজন হতে পারে।


Parsing Yes or No Input

System.out.print(
        "Do you want to continue? "
);

String answer =
        scanner
                .nextLine()
                .strip()
                .toLowerCase();

boolean shouldContinue =
        answer.equals("yes")
        || answer.equals("y");

Input accepted:

yes
YES
Yes
y
Y

Normalizing User Input

User input-এর শুরু বা শেষে extra whitespace থাকতে পারে।

String name =
        scanner
                .nextLine()
                .strip();

Input:

   Sakib   

Stored value:

Sakib

Case Normalization

String language =
        scanner
                .nextLine()
                .strip()
                .toLowerCase();

Input:

  JAVA

Stored value:

java

Invalid Integer Input

Code:

int age =
        scanner.nextInt();

User input:

twenty

Runtime error হতে পারে:

InputMismatchException

Program terminate করতে পারে।


Checking with hasNextInt()

Scanner-এর কাছে next token integer কি না check করা যায়।

if (scanner.hasNextInt()) {
    int age =
            scanner.nextInt();

    System.out.println(
            "Age: " + age
    );
} else {
    System.out.println(
            "Age must be an integer"
    );
}

Complete hasNextInt() Example

import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        Scanner scanner =
                new Scanner(System.in);

        System.out.print(
                "Enter your age: "
        );

        if (scanner.hasNextInt()) {
            int age =
                    scanner.nextInt();

            System.out.println(
                    "Age: " + age
            );
        } else {
            System.out.println(
                    "Invalid age"
            );
        }

        scanner.close();
    }
}

Checking with hasNextDouble()

if (scanner.hasNextDouble()) {
    double price =
            scanner.nextDouble();

    System.out.println(
            "Price: " + price
    );
} else {
    System.out.println(
            "Price must be a number"
    );
}

Other Scanner Check Methods

Common methods:

hasNext()
hasNextLine()
hasNextInt()
hasNextLong()
hasNextFloat()
hasNextDouble()
hasNextBoolean()

এগুলো next input expected type-এর কি না check করতে পারে।


Consuming Invalid Input

ধরা যাক invalid integer input দেওয়া হয়েছে।

if (scanner.hasNextInt()) {
    int age =
            scanner.nextInt();
} else {
    String invalidInput =
            scanner.next();

    System.out.println(
            "Invalid value: "
            + invalidInput
    );
}

Invalid token consume না করলে loop-এর মধ্যে একই invalid token বারবার পড়তে পারে।


Validation with Parsed String Input

String ageText =
        scanner
                .nextLine()
                .strip();

if (ageText.isBlank()) {
    System.out.println(
            "Age is required"
    );
} else {
    int age =
            Integer.parseInt(
                    ageText
            );

    System.out.println(
            "Age: " + age
    );
}

তবে non-numeric input-এর জন্য exception handling প্রয়োজন।


Exception Handling Preview

String ageText =
        scanner.nextLine();

try {
    int age =
            Integer.parseInt(
                    ageText.strip()
            );

    System.out.println(
            "Age: " + age
    );
} catch (NumberFormatException error) {
    System.out.println(
            "Age must be a valid integer"
    );
}

try-catch future lesson-এ বিস্তারিত শেখানো হবে।


Validating a Number Range

User integer দিলেও value meaningful নাও হতে পারে।

Example:

Age: -10

Parsing successful, কিন্তু value invalid।

int age =
        Integer.parseInt(
                scanner.nextLine()
        );

boolean ageValid =
        age >= 0
        && age <= 150;

Type validity এবং business validity আলাদা।


Type Validation vs Business Validation

Type Validation

Input integer কি?

20 → valid integer
twenty → invalid integer

Business Validation

Integer হলেও acceptable range-এর মধ্যে কি?

20 → valid age
-10 → invalid age
500 → invalid age

দুটিই প্রয়োজন হতে পারে।


Reading Several Values as Lines

import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        Scanner scanner =
                new Scanner(System.in);

        System.out.print(
                "Enter your name: "
        );

        String name =
                scanner
                        .nextLine()
                        .strip();

        System.out.print(
                "Enter your age: "
        );

        int age =
                Integer.parseInt(
                        scanner
                                .nextLine()
                                .strip()
                );

        System.out.print(
                "Enter your score: "
        );

        double score =
                Double.parseDouble(
                        scanner
                                .nextLine()
                                .strip()
                );

        System.out.println();
        System.out.println(
                "Name: " + name
        );

        System.out.println(
                "Age: " + age
        );

        System.out.println(
                "Score: " + score
        );

        scanner.close();
    }
}

এই style consistent এবং newline issue কমায়।


Scanner Delimiter

Defaultভাবে Scanner whitespace delimiter হিসেবে ব্যবহার করে।

Whitespace-এর মধ্যে থাকতে পারে:

  • Space
  • Tab
  • Newline

Input:

10 20 30

Code:

int firstNumber =
        scanner.nextInt();

int secondNumber =
        scanner.nextInt();

int thirdNumber =
        scanner.nextInt();

Values:

10
20
30

এক line-এ থাকলেও আলাদা token হিসেবে পড়া যায়।


Custom Delimiter Preview

Comma-separated input পড়তে delimiter change করা যায়।

Input:

Java,Go,Python
scanner.useDelimiter(",");

তারপর:

String firstLanguage =
        scanner.next();

Custom delimiter advanced use case।

Simple console application-এ default behaviour যথেষ্ট।


Reading Command-Line vs Scanner Input

Command-line argument:

java Main Sakib

Read:

String name = args[0];

Scanner input:

Enter your name: Sakib

Read:

String name =
        scanner.nextLine();

Difference:

  • Command-line argument program start করার সময় দেওয়া হয়
  • Scanner input program চলার সময় interactiveভাবে দেওয়া হয়

Closing the Scanner

শেষে:

scanner.close();

এটি Scanner resource close করে।

Complete:

Scanner scanner =
        new Scanner(System.in);

// Read input

scanner.close();

What Happens When Scanner Is Closed?

scanner.close() underlying System.in stream-ও close করতে পারে।

এরপর একই application-এ নতুন Scanner দিয়ে System.in পড়ার চেষ্টা problem তৈরি করতে পারে।

Simple program-এ শেষে close করা ঠিক।


Do Not Close Scanner Too Early

Wrong:

Scanner scanner =
        new Scanner(System.in);

String name =
        scanner.nextLine();

scanner.close();

int age =
        scanner.nextInt();

Scanner close হওয়ার পর input পড়া যাবে না।

Close সব input complete হওয়ার পরে করুন।


Avoid Multiple Scanners for System.in

Avoid:

Scanner firstScanner =
        new Scanner(System.in);

Scanner secondScanner =
        new Scanner(System.in);

একাধিক Scanner একই input stream manage করলে unexpected behaviour হতে পারে।

একটি application flow-এর জন্য সাধারণত একটি Scanner reuse করুন।


Try-With-Resources Preview

Resource automatically close করতে:

try (
        Scanner scanner =
                new Scanner(System.in)
) {
    String name =
            scanner.nextLine();

    System.out.println(name);
}

এটি try-with-resources।

Exception handling module-এ বিস্তারিত শেখানো হবে।


Prompt Design

Good prompt user-কে clear instruction দেয়।

Poor:

Input:

Better:

Enter your age in years:

Poor:

Value:

Better:

Enter the course price in BDT:

Include Expected Format

Enter your date of birth in YYYY-MM-DD format:
Enter true or false:
Enter a whole number between 0 and 100:

Clear prompt invalid input কমায়।


Do Not Include Sensitive Input in Plain Console

Scanner password input hide করে না।

String password =
        scanner.nextLine();

User যা type করবে, console-এ visible থাকবে।

Production password input-এর জন্য secure console API বা UI component ব্যবহার করতে হয়।


Reading Password with Console Preview

Java Console password character hide করতে পারে:

Console console =
        System.console();

char[] password =
        console.readPassword(
                "Enter password: "
        );

তবে IDE-এর Run window-তে System.console() null হতে পারে।

এই lesson-এ আমরা normal text input-এ focus করব।


Locale and Decimal Input

Scanner.nextDouble() locale-sensitive হতে পারে।

কিছু locale-এ decimal separator:

,

অন্য locale-এ:

.

Example:

99.50

বা:

99,50

Environment অনুযায়ী parsing behaviour ভিন্ন হতে পারে।

Predictable format-এর জন্য explicit locale configure করা যায়।

import java.util.Locale;

scanner.useLocale(
        Locale.US
);

তাহলে decimal point হিসেবে . expected হবে।


Using Locale.ROOT for Text Normalization

Text lowercase করতে:

String answer =
        scanner
                .nextLine()
                .strip()
                .toLowerCase(
                        Locale.ROOT
                );

Production code-এ locale-neutral command normalize করতে এটি useful।


Scanner Is Convenient but Not the Fastest

Scanner beginner-friendly এবং readable।

তবে large input processing-এর জন্য এটি তুলনামূলক slow হতে পারে।

Alternative:

  • BufferedReader
  • Custom parser
  • NIO input
  • Framework-specific request parser

Beginner console application-এর জন্য Scanner যথেষ্ট।


Interactive Greeting Program

import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        Scanner scanner =
                new Scanner(System.in);

        System.out.print(
                "Enter your name: "
        );

        String name =
                scanner
                        .nextLine()
                        .strip();

        System.out.print(
                "Enter your country: "
        );

        String country =
                scanner
                        .nextLine()
                        .strip();

        System.out.println();
        System.out.println(
                "Hello, " + name + "!"
        );

        System.out.println(
                "Country: " + country
        );

        scanner.close();
    }
}

Interactive Addition Program

import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        Scanner scanner =
                new Scanner(System.in);

        System.out.print(
                "Enter the first number: "
        );

        int firstNumber =
                Integer.parseInt(
                        scanner
                                .nextLine()
                                .strip()
                );

        System.out.print(
                "Enter the second number: "
        );

        int secondNumber =
                Integer.parseInt(
                        scanner
                                .nextLine()
                                .strip()
                );

        int total =
                firstNumber
                + secondNumber;

        System.out.println(
                "Total: " + total
        );

        scanner.close();
    }
}

Interaction:

Enter the first number: 10
Enter the second number: 20
Total: 30

Interactive Average Calculator

import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        Scanner scanner =
                new Scanner(System.in);

        System.out.print(
                "Enter mathematics mark: "
        );

        int mathematicsMark =
                Integer.parseInt(
                        scanner
                                .nextLine()
                                .strip()
                );

        System.out.print(
                "Enter English mark: "
        );

        int englishMark =
                Integer.parseInt(
                        scanner
                                .nextLine()
                                .strip()
                );

        System.out.print(
                "Enter science mark: "
        );

        int scienceMark =
                Integer.parseInt(
                        scanner
                                .nextLine()
                                .strip()
                );

        int totalMarks =
                mathematicsMark
                + englishMark
                + scienceMark;

        double averageMark =
                totalMarks / 3.0;

        System.out.println();
        System.out.println(
                "Total: " + totalMarks
        );

        System.out.println(
                "Average: " + averageMark
        );

        scanner.close();
    }
}

Interactive Product Order Program

import java.util.Scanner;

public class Main {

    static final int DELIVERY_CHARGE = 80;

    public static void main(String[] args) {
        Scanner scanner =
                new Scanner(System.in);

        System.out.print(
                "Enter product name: "
        );

        String productName =
                scanner
                        .nextLine()
                        .strip();

        System.out.print(
                "Enter product price: "
        );

        int productPrice =
                Integer.parseInt(
                        scanner
                                .nextLine()
                                .strip()
                );

        System.out.print(
                "Enter quantity: "
        );

        int quantity =
                Integer.parseInt(
                        scanner
                                .nextLine()
                                .strip()
                );

        int subtotal =
                productPrice * quantity;

        int total =
                subtotal + DELIVERY_CHARGE;

        System.out.println();
        System.out.println(
                "Product: " + productName
        );

        System.out.println(
                "Price: " + productPrice
        );

        System.out.println(
                "Quantity: " + quantity
        );

        System.out.println(
                "Subtotal: " + subtotal
        );

        System.out.println(
                "Delivery charge: "
                + DELIVERY_CHARGE
        );

        System.out.println(
                "Total: " + total
        );

        scanner.close();
    }
}

Interactive Course Enrollment Program

import java.util.Locale;
import java.util.Scanner;

public class Main {

    static final int MINIMUM_AGE = 18;

    public static void main(String[] args) {
        Scanner scanner =
                new Scanner(System.in);

        System.out.print(
                "Enter your full name: "
        );

        String fullName =
                scanner
                        .nextLine()
                        .strip();

        System.out.print(
                "Enter your age: "
        );

        int age =
                Integer.parseInt(
                        scanner
                                .nextLine()
                                .strip()
                );

        System.out.print(
                "Is your email verified? "
                + "Enter yes or no: "
        );

        String emailAnswer =
                scanner
                        .nextLine()
                        .strip()
                        .toLowerCase(
                                Locale.ROOT
                        );

        boolean emailVerified =
                emailAnswer.equals("yes")
                || emailAnswer.equals("y");

        boolean canEnroll =
                age >= MINIMUM_AGE
                && emailVerified;

        System.out.println();
        System.out.println(
                "Learner: " + fullName
        );

        System.out.println(
                "Age: " + age
        );

        System.out.println(
                "Email verified: "
                + emailVerified
        );

        System.out.println(
                "Can enroll: "
                + canEnroll
        );

        scanner.close();
    }
}

Complete Student Result Program

import java.util.Scanner;

public class Main {

    static final int PASSING_MARK = 40;

    public static void main(String[] args) {
        Scanner scanner =
                new Scanner(System.in);

        System.out.print(
                "Enter student name: "
        );

        String studentName =
                scanner
                        .nextLine()
                        .strip();

        System.out.print(
                "Enter mathematics mark: "
        );

        int mathematicsMark =
                Integer.parseInt(
                        scanner
                                .nextLine()
                                .strip()
                );

        System.out.print(
                "Enter English mark: "
        );

        int englishMark =
                Integer.parseInt(
                        scanner
                                .nextLine()
                                .strip()
                );

        System.out.print(
                "Enter science mark: "
        );

        int scienceMark =
                Integer.parseInt(
                        scanner
                                .nextLine()
                                .strip()
                );

        int totalMarks =
                mathematicsMark
                + englishMark
                + scienceMark;

        double averageMark =
                totalMarks / 3.0;

        boolean passed =
                mathematicsMark >= PASSING_MARK
                && englishMark >= PASSING_MARK
                && scienceMark >= PASSING_MARK;

        String result =
                passed
                        ? "Passed"
                        : "Failed";

        System.out.println();
        System.out.println(
                "Student: " + studentName
        );

        System.out.println(
                "Mathematics: "
                + mathematicsMark
        );

        System.out.println(
                "English: " + englishMark
        );

        System.out.println(
                "Science: " + scienceMark
        );

        System.out.println(
                "Total: " + totalMarks
        );

        System.out.println(
                "Average: " + averageMark
        );

        System.out.println(
                "Result: " + result
        );

        scanner.close();
    }
}

Common Error: Missing Import

Wrong:

public class Main {

    public static void main(String[] args) {
        Scanner scanner =
                new Scanner(System.in);
    }
}

Compiler Scanner চিনবে না।

Correct:

import java.util.Scanner;

Common Error: Creating Scanner Without new

Wrong:

Scanner scanner =
        Scanner(System.in);

Correct:

Scanner scanner =
        new Scanner(System.in);

Common Error: Wrong Input Source

Wrong:

Scanner scanner =
        new Scanner(System.out);

System.out output stream।

Keyboard input-এর জন্য:

Scanner scanner =
        new Scanner(System.in);

Common Error: Using next() for Full Name

String fullName =
        scanner.next();

Input:

Md Sakib

Stored value:

Md

Correct:

String fullName =
        scanner.nextLine();

Common Error: Mixing nextInt() and nextLine()

int age =
        scanner.nextInt();

String name =
        scanner.nextLine();

name empty হতে পারে।

Fix:

int age =
        scanner.nextInt();

scanner.nextLine();

String name =
        scanner.nextLine();

অথবা সব input nextLine() দিয়ে পড়ুন।


Common Error: Invalid Integer Input

int age =
        scanner.nextInt();

Input:

twenty

InputMismatchException হতে পারে।

hasNextInt() বা String parsing with validation ব্যবহার করুন।


Common Error: Parsing Without Trimming

int age =
        Integer.parseInt(
                " 20 "
        );

Error হতে পারে।

Correct:

int age =
        Integer.parseInt(
                " 20 ".strip()
        );

Common Error: Closing Scanner Too Early

Scanner scanner =
        new Scanner(System.in);

scanner.close();

String name =
        scanner.nextLine();

Scanner already closed।

সব input শেষে close করুন।


Common Error: Multiple Scanner Objects

Scanner nameScanner =
        new Scanner(System.in);

Scanner ageScanner =
        new Scanner(System.in);

Avoid করুন।

একটি Scanner object reuse করুন।


Common Error: Assuming nextBoolean() Accepts Yes

boolean answer =
        scanner.nextBoolean();

Input:

yes

Invalid।

Either prompt:

Enter true or false:

অথবা String পড়ে custom parse করুন।


Common Error: No Prompt

int age =
        scanner.nextInt();

User জানে না কী input দিতে হবে।

Better:

System.out.print(
        "Enter your age: "
);

Common Error: No Range Validation

int mark =
        Integer.parseInt(
                scanner.nextLine()
        );

Input:

500

Parsing valid, কিন্তু mark invalid।

Check:

boolean valid =
        mark >= 0
        && mark <= 100;

Common Error: Using Input Without Normalization

String answer =
        scanner.nextLine();

boolean confirmed =
        answer.equals("yes");

Input:

 YES 

False হবে।

Better:

String answer =
        scanner
                .nextLine()
                .strip()
                .toLowerCase();

Common Error: Trusting User Input

User input:

  • Missing হতে পারে
  • Blank হতে পারে
  • Wrong type হতে পারে
  • Wrong range হতে পারে
  • Malicious হতে পারে
  • Unexpected format-এ হতে পারে

Professional application-এ input কখনো blindly trust করা উচিত নয়।


Input Validation Checklist

Input নেওয়ার পর check করুন:

  1. Value missing কি না
  2. Value blank কি না
  3. Expected type কি না
  4. Expected format কি না
  5. Allowed range-এর মধ্যে কি না
  6. Allowed option-এর একটি কি না
  7. Leading/trailing whitespace আছে কি না
  8. Case normalize প্রয়োজন কি না
  9. Input length acceptable কি না
  10. Sensitive information কি না

Scanner Method Summary

Methodকাজ
next()একটি token পড়ে
nextLine()পুরো line পড়ে
nextInt()Integer token পড়ে
nextLong()long token পড়ে
nextFloat()float token পড়ে
nextDouble()double token পড়ে
nextBoolean()Boolean token পড়ে
hasNext()Next token আছে কি না
hasNextLine()Next line আছে কি না
hasNextInt()Next token integer কি না
hasNextDouble()Next token double কি না
close()Scanner close করে

Recommended Beginner Strategy

এই course-এর console programগুলোর জন্য recommended approach:

  1. একটি Scanner তৈরি করুন
  2. সব input nextLine() দিয়ে পড়ুন
  3. .strip() দিয়ে normalize করুন
  4. Number-এর জন্য parse method ব্যবহার করুন
  5. Input validate করুন
  6. সব input শেষে Scanner close করুন

Example:

String ageText =
        scanner
                .nextLine()
                .strip();

int age =
        Integer.parseInt(ageText);

এতে token এবং newline mixing issue কম হয়।


Important Terms

User Input

Program চলার সময় user-এর দেওয়া data।

Standard Input

Program-এর default input stream।

System.in

Scanner

Text input read এবং parse করার Java utility class।

Prompt

User-কে কী input দিতে হবে তা বোঝানো message।

Token

Whitespace বা delimiter দিয়ে আলাদা করা input-এর একটি অংশ।

Input Buffer

Program পড়ার আগে input data temporaryভাবে যেখানে থাকে।

Newline

Enter press করার ফলে তৈরি line-ending character।

Parsing

Text value interpret করে numeric বা boolean value তৈরি করা।

Validation

Input acceptable কি না check করা।

Normalization

Input standard form-এ আনা।

Example:

  • Whitespace remove
  • Lowercase করা

InputMismatchException

Scanner expected type না পেলে হতে পারে এমন runtime exception।

NumberFormatException

Invalid numeric String parse করলে হতে পারে এমন exception।

Resource

Program যে external বা system facility ব্যবহার করে এবং পরে release করতে হয়।


Practice Exercise 1: Import and Create Scanner

একটি Java program লিখুন, যেখানে:

  • Scanner import করবেন
  • Scanner object তৈরি করবেন
  • Program শেষে close করবেন

এখন কোনো input পড়ার প্রয়োজন নেই।


Practice Exercise 2: Read a Full Name

User-এর full name পড়ুন।

Input:

Md Samiul Alim Sakib

Expected output:

Welcome, Md Samiul Alim Sakib

nextLine() ব্যবহার করুন।


Practice Exercise 3: next() vs nextLine()

Input:

Java and OOP Foundation

একবার next() এবং একবার nextLine() ব্যবহার করে result compare করুন।

Explain করুন কেন output আলাদা।


Practice Exercise 4: Read an Integer

User-এর age পড়ুন।

Expected interaction:

Enter your age: 20
Next year you will be 21

Practice Exercise 5: Read a Decimal

User-এর course price পড়ুন।

Expected interaction:

Enter course price: 4990.50
Price after adding 100: 5090.5

Practice Exercise 6: Read a Boolean

Prompt:

Is enrollment open? Enter true or false:

Input read করে output দিন:

Enrollment open: true

Practice Exercise 7: Fix the Skipped Input

নিচের code fix করুন:

System.out.print(
        "Enter your age: "
);

int age =
        scanner.nextInt();

System.out.print(
        "Enter your full name: "
);

String fullName =
        scanner.nextLine();

Extra newline consume করুন।


Practice Exercise 8: Use Only nextLine()

নিচের inputগুলো শুধু nextLine() দিয়ে পড়ুন:

  • Name
  • Age
  • Price
  • Active status

তারপর parse করুন:

  • Age → int
  • Price → double
  • Active → boolean

Practice Exercise 9: Normalize Input

Input:

   JAVA   

Expected output:

java

Use:

  • nextLine()
  • strip()
  • toLowerCase()

Practice Exercise 10: Yes or No Input

Prompt:

Do you want to continue? Enter yes or no:

Accepted positive input:

yes
y
YES
Y

Boolean shouldContinue তৈরি করুন।


Practice Exercise 11: Check Integer Input

hasNextInt() ব্যবহার করে age input validate করুন।

Valid input:

20

Output:

Age: 20

Invalid input:

twenty

Output:

Age must be an integer

Practice Exercise 12: Check Decimal Input

hasNextDouble() ব্যবহার করে price validate করুন।

Invalid input হলে meaningful error দেখান।


Practice Exercise 13: Age Range Validation

User-এর age পড়ুন।

Valid range:

0 to 150

Output:

Valid age: true

অথবা:

Valid age: false

Practice Exercise 14: Mark Validation

User-এর mark পড়ুন।

Rules:

  • Integer হতে হবে
  • Minimum 0
  • Maximum 100

Valid বা invalid status print করুন।


Practice Exercise 15: Two-Number Calculator

User-এর কাছ থেকে দুটি integer নিন।

Print করুন:

  • Addition
  • Subtraction
  • Multiplication
  • Division
  • Remainder

Zero division-এর possibility নিয়ে ভাবুন।


Practice Exercise 16: Full Name and Age

Programটি নেবে:

  • Full name
  • Age
  • Country

Output:

Name: Sakib
Age: 20
Country: Bangladesh

Practice Exercise 17: Product Order

Input:

  • Product name
  • Unit price
  • Quantity

Calculate:

subtotal = unit price × quantity

Output সব informationসহ print করুন।


Practice Exercise 18: Student Result

Input:

  • Student name
  • Mathematics mark
  • English mark
  • Science mark

Calculate:

  • Total
  • Decimal average
  • Each subject passed কি না
  • Overall result

Passing mark:

40

Practice Exercise 19: Course Enrollment

Input:

  • Full name
  • Age
  • Email verified: yes/no
  • Enrollment open: yes/no

Rules:

  • Minimum age 18
  • Email verified হতে হবে
  • Enrollment open হতে হবে

Final canEnroll print করুন।


Practice Exercise 20: Duration Conversion

User-এর কাছ থেকে total seconds নিন।

Calculate:

  • Hours
  • Minutes
  • Remaining seconds

Input:

3675

Output:

Hours: 1
Minutes: 1
Seconds: 15

Practice Exercise 21: Explain the Newline Problem

নিজের ভাষায় ব্যাখ্যা করুন:

  1. nextInt() কী পড়ে?
  2. Enter key-এর newline কোথায় থাকে?
  3. পরবর্তী nextLine() কেন empty String return করতে পারে?
  4. Problem fix করার দুটি উপায় কী?

Practice Exercise 22: Parsing Error

Input:

twenty

Code:

int age =
        Integer.parseInt(
                scanner.nextLine()
        );

কী exception হতে পারে?

User-friendly handling-এর একটি basic version লিখুন।


Practice Exercise 23: Scanner Lifecycle

নিচের code-এ problem identify করুন:

Scanner scanner =
        new Scanner(System.in);

String name =
        scanner.nextLine();

scanner.close();

int age =
        scanner.nextInt();

Correct order লিখুন।


Practice Exercise 24: Multiple Scanner Problem

একই System.in-এর জন্য multiple Scanner avoid করা উচিত কেন?

একটি Scanner reuse করে example লিখুন।


Practice Exercise 25: Explain in Your Own Words

নিজের ভাষায় উত্তর দিন:

  1. User input কী?
  2. System.in কী?
  3. Scanner কী?
  4. Scanner import কেন করতে হয়?
  5. next() এবং nextLine()-এর পার্থক্য কী?
  6. nextInt() কী করে?
  7. hasNextInt() কেন useful?
  8. nextInt()-এর পরে nextLine() কেন skip হতে পারে?
  9. সব input nextLine() দিয়ে পড়ার সুবিধা কী?
  10. Parsing কী?
  11. Input normalization কী?
  12. Type validation এবং business validation-এর পার্থক্য কী?
  13. Scanner কখন close করা উচিত?
  14. Multiple Scanner কেন avoid করা উচিত?
  15. User input blindly trust করা উচিত নয় কেন?

Knowledge Check

Question 1

Console input-এর standard stream কোনটি?

Question 2

Scanner কোন package-এর class?

Question 3

Scanner import statement কী?

Question 4

Keyboard input-এর জন্য Scanner object কীভাবে তৈরি করা হয়?

Question 5

পুরো line পড়ার method কী?

Question 6

একটি token পড়ার method কী?

Question 7

Integer পড়ার method কী?

Question 8

Decimal পড়ার common method কী?

Question 9

Boolean পড়ার method কী?

Question 10

Prompt-এর জন্য print() কেন useful?

Question 11

next() কি spaceসহ full name পড়ে?

Question 12

nextLine() কি spaceসহ full line পড়ে?

Question 13

nextInt()-এর পরে nextLine() skip হতে পারে কেন?

Question 14

Leftover newline consume করতে কী করা যায়?

Question 15

সব input line হিসেবে পড়ে integer বানানোর method কী?

Question 16

hasNextInt() কী check করে?

Question 17

nextInt() invalid text পেলে কোন exception হতে পারে?

Question 18

Integer.parseInt() invalid text পেলে কোন exception হতে পারে?

Question 19

nextBoolean() কি "yes" accept করে?

Question 20

Input-এর surrounding whitespace remove করার method কী?

Question 21

Input lowercase করতে কোন method ব্যবহার করা যায়?

Question 22

Input type-correct হলেই কি business-valid হয়?

Question 23

Scanner কখন close করা উচিত?

Question 24

একই System.in-এর জন্য multiple Scanner recommended কি?

Question 25

Simple beginner program-এর recommended input strategy কী?


Knowledge Check Answers

Answer 1

System.in

Answer 2

java.util

Answer 3

import java.util.Scanner;

Answer 4

Scanner scanner =
        new Scanner(System.in);

Answer 5

nextLine()

Answer 6

next()

Answer 7

nextInt()

Answer 8

nextDouble()

Answer 9

nextBoolean()

Answer 10

print() new line তৈরি করে না, তাই user prompt-এর একই line-এ input দিতে পারে।

Answer 11

না। next() whitespace পর্যন্ত একটি token পড়ে।

Answer 12

হ্যাঁ।

Answer 13

nextInt() integer token পড়ে, কিন্তু Enter-এর newline buffer-এ রেখে দিতে পারে। পরবর্তী nextLine() সেই newline পড়ে empty String return করে।

Answer 14

একটি extra:

scanner.nextLine();

call করা যায়।

Answer 15

Integer.parseInt(
        scanner.nextLine()
)

Answer 16

পরবর্তী token valid integer কি না।

Answer 17

InputMismatchException

Answer 18

NumberFormatException

Answer 19

না। সাধারণত true বা false expected।

Answer 20

strip()

Answer 21

toLowerCase()

Answer 22

না। যেমন 500 valid integer, কিন্তু age বা mark হিসেবে invalid হতে পারে।

Answer 23

সব input operation শেষ হওয়ার পরে।

Answer 24

না। সাধারণত একটি Scanner reuse করা উচিত।

Answer 25

সব input nextLine() দিয়ে পড়া, normalize করা এবং প্রয়োজন অনুযায়ী parse করা।


Lesson Summary

এই lesson-এ আমরা শিখেছি:

  • User input program-কে interactive করে
  • System.in standard input stream
  • Scanner console input পড়তে সাহায্য করে
  • Scanner ব্যবহার করতে java.util.Scanner import করতে হয়
  • Keyboard input-এর জন্য new Scanner(System.in) ব্যবহার করা হয়
  • Prompt user-কে expected input বোঝায়
  • nextLine() পুরো line পড়ে
  • next() একটি token পড়ে
  • nextInt() integer token পড়ে
  • nextDouble() decimal token পড়ে
  • nextBoolean() boolean token পড়ে
  • Multiple input একই Scanner দিয়ে পড়া যায়
  • Token-based method newline buffer-এ রেখে দিতে পারে
  • nextInt()-এর পরে nextLine() skip হওয়া common issue
  • Extra nextLine() leftover newline consume করতে পারে
  • সব input nextLine() দিয়ে পড়ে parse করা consistent approach
  • .strip() input normalize করে
  • .toLowerCase() case normalize করতে সাহায্য করে
  • hasNextInt() এবং hasNextDouble() type check করে
  • Invalid Scanner input InputMismatchException তৈরি করতে পারে
  • Invalid String parsing NumberFormatException তৈরি করতে পারে
  • Type-valid input business-invalid হতে পারে
  • Input range এবং format validate করা প্রয়োজন
  • Scanner সব input শেষে close করা উচিত
  • Scanner খুব early close করা যাবে না
  • একই System.in-এর জন্য multiple Scanner avoid করা উচিত
  • User input কখনো blindly trust করা উচিত নয়
  • Interactive console program-এ input, processing এবং output clearভাবে separate রাখা ভালো

Next Lesson

পরবর্তী lesson-এ আমরা conditional statements শিখব।

আমরা জানব:

  • Boolean condition
  • if statement
  • if-else
  • else-if
  • Nested condition
  • Multiple condition
  • Range validation
  • Early decision
  • Conditional flow
  • Common if-related error
  • Grade এবং eligibility logic তৈরি করা