Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Java

Cách đọc dữ liệu từ người dùng dùng class Console trong Java

Class java.io.Console cung cấp cách đọc/ghi console đơn giản, an toàn (đặc biệt cho password). Lấy instance bằng System.console().

Ví dụ hoàn chỉnh

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;
    }
    
    void display() {
        System.out.println("\nDetails..............");
        System.out.println("Name: " + name);
        System.out.println("Age: " + age);
        System.out.println("Percent: " + percent);
        System.out.println("Nationality: " + (isLocal ? "Indian" : "Foreigner"));
        System.out.println("Grade: " + grade);
    }
}

public class ReadDataConsole {
    public static void main(String args[]) throws IOException {
        Console console = System.console();
        if (console == null) {
            System.err.println("Console not supported (running in IDE?)");
            System.exit(1);
        }
        
        System.out.print("Enter name: ");
        String name = console.readLine();
        
        System.out.print("Enter age: ");
        int age = Integer.parseInt(console.readLine());
        
        System.out.print("Enter percent: ");
        float percent = Float.parseFloat(console.readLine());
        
        System.out.print("Local? (true/false): ");
        boolean isLocal = Boolean.parseBoolean(console.readLine());
        
        System.out.print("Grade (A/B/C/D): ");
        char grade = console.readLine().charAt(0);
        
        new Student(name, age, percent, isLocal, grade).display();
    }
}

Kết quả

Enter name: Krishna
Enter age: 26
Enter percent: 86
Local? (true/false): true
Grade (A/B/C/D): A

Details..............
Name: Krishna
Age: 26
Percent: 86.0
Nationality: Indian
Grade: A

Lưu ý quan trọng

  • Không hoạt động trong IDE (Eclipse, IntelliJ, VS Code) vì IDE không cung cấp console thật. Chỉ chạy được từ terminal/command line.
  • readPassword(): Đọc mật khẩu không hiển thị trên màn hình (trả về char[]).
  • Cần parse kiểu dữ liệu thủ công (Integer.parseInt, v.v.).

So sánh với Scanner

Đặc điểmConsoleScanner
Đọc password an toànCó (readPassword)Không
Chạy trong IDEKhôngCó
PerformanceTốt hơnChậm hơn
Buffer readingCó (readLine)Có (nextLine)