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

Chương trình Java đọc số từ Standard Input


Trong bài viết này, chúng ta sẽ tìm hiểu cách đọc một số từ standard input trong Java. Phương thức Scanner.nextInt() dùng để đọc số. Phương thức java.util.Scanner.nextInt() quét token tiếp theo như int.

Dưới đây là minh họa:

Đầu vào

Giả sử đầu vào:

55

Đầu ra

Kết quả mong đợi:

Giá trị đầu vào là 55

Thuật toán

Bước 1 - BẮT ĐẦU
Bước 2 - Khai báo số nguyên: value
Bước 3 - Nhắc người dùng nhập số hoặc định nghĩa trước
Bước 4 - Đọc giá trị
Bước 5 - Hiển thị giá trị
Bước 6 - DỪNG

Ví dụ 1: Dùng Scanner.nextInt()

Người dùng nhập dựa trên lời nhắc. Thử trực tiếp trong coding ground.

import java.util.Scanner;
public class PrintNumber {
    public static void main(String[] args) {
        int value;
        System.out.println("Required packages have been imported");
        System.out.println("Variable to store value is defined");
        Scanner reader = new Scanner(System.in);
        System.out.println("A reader object has been defined\n");
        System.out.print("Enter a number: ");
        value = reader.nextInt();
        System.out.println("The nextInt method is used to read the number");
        System.out.println("The number is: ");
        System.out.println(value);
    }
}

Đầu ra

Required packages have been imported
Variable to store value is defined
A reader object has been defined
Enter a number: 55
The nextInt method is used to read the number
The number is: 55

Ví dụ 2: Dùng InputStreamReader và BufferedReader

Người dùng nhập dựa trên lời nhắc. Thử trực tiếp trong coding ground.

import java.io.*;
public class readNum {
    public static void main(String args[]) throws IOException {
        InputStreamReader read = new InputStreamReader(System.in);
        System.out.println("An object of InputStreamReader class is created");
        BufferedReader in = new BufferedReader(read);
        System.out.println("A constructor of the BufferedReader class is created");
        System.out.println("Enter a number: ");
        int number = Integer.parseInt(in.readLine());
        System.out.println("The number is: " + number);
    }
}

Đầu ra

An object of InputStreamReader class is created
A constructor of the BufferedReader class is created
Enter a number: 
The number is: 45