কম্পিউটার টিউটোরিয়াল

জাভাতে Console ক্লাস ব্যবহার করে ইউজার থেকে ডেটা পড়া

Console ক্লাস

java.io.Console ক্লাস কনসোল (কিবোর্ড/স্ক্রিন) ডিভাইস থেকে ডেটা পড়তে/লিখতে ব্যবহৃত হয়। এতে readLine() মেথড আছে যা কিবোর্ড থেকে একটি লাইন পড়ে। System.console() মেথড দিয়ে Console অবজেক্ট পাওয়া যায়।

গুরুত্বপূর্ণ নোট: IDE (Eclipse, IntelliJ) এর কনসোল নন-ইন্টারঅ্যাক্টিভ এনভায়রনমেন্ট, তাই সেখানে System.console() null রিটার্ন করে। এই প্রোগ্রাম কমান্ড প্রম্পট/টার্মিনাল থেকে রান করতে হবে।

উদাহরণ: Console দিয়ে ইউজার ইনপুট নেওয়া

import java.io.Console;
import java.io.IOException;

class Student {
    String name;
    int age;
    float percent;
    boolean isLocal;
    char grade;

    Student(String name, int age, float percent, boolean isLocal, char grade) {
        this.name = name;
        this.age = age;
        this.percent = percent;
        this.isLocal = isLocal;
        this.grade = grade;
    }

    public void displayDetails() {
        System.out.println("Details..............");
        System.out.println("Name: " + this.name);
        System.out.println("Age: " + this.age);
        System.out.println("Percent: " + this.percent);
        System.out.println("Nationality: " + (this.isLocal ? "Indian" : "Foreigner"));
        System.out.println("Grade: " + this.grade);
    }
}

public class ReadData {
    public static void main(String args[]) throws IOException {
        Console console = System.console();
        
        // নন-ইন্টারঅ্যাক্টিভ এনভায়রনমেন্ট চেক
        if (console == null) {
            System.out.println("Console is not supported in this environment (IDE). Run from terminal.");
            System.exit(1);
        }

        System.out.println("Enter your name: ");
        String name = console.readLine();
        
        System.out.println("Enter your age: ");
        int age = Integer.parseInt(console.readLine());
        
        System.out.println("Enter your percent: ");
        float percent = Float.parseFloat(console.readLine());
        
        System.out.println("Are you local (enter true or false): ");
        boolean isLocal = Boolean.parseBoolean(console.readLine());
        
        System.out.println("Enter your grade (A, B, C, or D): ");
        char grade = console.readLine().toCharArray()[0];

        Student std = new Student(name, age, percent, isLocal, grade);
        std.displayDetails();
    }
}

আউটপুট (টার্মিনালে রান করলে)

Enter your name: Krishna
Enter your age: 26
Enter your percent: 86
Are you local (enter true or false): true
Enter your grade (enter A, or, B or, C or, D): A
Details..............
Name: Krishna
Age: 26
Percent: 86.0
Nationality: Indian
Grade: A

বিকল্প: IDE-এ কাজ করার জন্য Scanner (new Scanner(System.in)) বা BufferedReader ব্যবহার করা ভালো।

  1. জাভাতে ফোল্ডার থেকে শুধু ডাইরেক্টরি পাওয়া

  2. জাভাতে প্রিমিটিভ ডেটাকে র‍্যাপার ক্লাসে কনভার্ট করার পদ্ধতি

  3. জাভাতে CSV ফাইল থেকে ডেটা পড়া

  4. জাভাতে প্রপার্টিজ ফাইল থেকে ডেটা পড়া