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

Chương trình Java nhận đầu vào từ người dùng


Trong bài viết này, chúng ta sẽ tìm hiểu cách nhận đầu vào từ người dùng trong Java. Việc này đạt được bằng đối tượng Scanner. Phương thức Scanner.nextInt() dùng để lấy đầu vào số nguyên. Phương thức java.util.Scanner.nextInt() quét token tiếp theo của đầu vào như một int.

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

Đầu vào

Giả sử đầu vào:

Hello, I am John!

Đầu ra

Kết quả mong đợi:

Chuỗi đầu vào là: Hello, I am John!

Thuật toán

Bước 1 - BẮT ĐẦU
Bước 2 - Khai báo chuỗi: value
Bước 3 - Nhắc người dùng nhập chuỗi
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.nextLine()

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 PrintString {
    public static void main(String[] args) {
        String value;
        Scanner scanner = new Scanner(System.in);
        System.out.println("A reader object has been defined");
        System.out.print("Enter a string: ");
        value = scanner.nextLine();
        System.out.println("The nextLine method is used to read the string value");
        System.out.println("The string is: ");
        System.out.println(value);
    }
}

Đầu ra

A reader object has been defined
Enter a string: Good Morning!
The nextLine method is used to read the string value
The string is: Good Morning!

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());
    }
}

Đầu ra

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