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

Cách đọc từ đầu vào chuẩn (standard input) trong Java

Đầu vào chuẩn (stdin) có thể được biểu diễn bởi System.in trong Java. System.in là một instance của lớp InputStream. Điều này có nghĩa là tất cả các phương thức của nó hoạt động trên byte, không phải Strings. Để đọc bất kỳ dữ liệu nào từ bàn phím, chúng ta có thể sử dụng либо lớp Reader hoặc lớp Scanner.

Ví dụ 1: Sử dụng BufferedReader

import java.io.*;

public class ReadDataFromInput {
    public static void main(String[] args) {
        int firstNum, secondNum, result;
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        try {
            System.out.println("Nhập số thứ nhất:");
            firstNum = Integer.parseInt(br.readLine());
            System.out.println("Nhập số thứ hai:");
            secondNum = Integer.parseInt(br.readLine());
            result = firstNum * secondNum;
            System.out.println("Kết quả là: " + result);
        } catch (IOException ioe) {
            System.out.println(ioe);
        }
    }
}

Kết quả

Nhập số thứ nhất: 15
Nhập số thứ hai: 20
Kết quả là: 300

Ví dụ 2: Sử dụng Scanner

import java.util.*;

public class ReadDataFromScanner {
    public static void main(String[] args) {
        int firstNum, secondNum, result;
        Scanner scanner = new Scanner(System.in);
        System.out.println("Nhập số thứ nhất:");
        firstNum = Integer.parseInt(scanner.nextLine());
        System.out.println("Nhập số thứ hai:");
        secondNum = Integer.parseInt(scanner.nextLine());
        result = firstNum * secondNum;
        System.out.println("Kết quả là: " + result);
    }
}

Kết quả

Nhập số thứ nhất: 20
Nhập số thứ hai: 25
Kết quả là: 500