Xem một số cách đọc đầu vào từ console trong Java:
Ví dụ 1: Scanner
import java.util.Scanner; public class Demo{ public static void main(String args[]){ Scanner my_scan = new Scanner(System.in); String my_str = my_scan.nextLine(); System.out.println("The string is "+my_str); int my_val = my_scan.nextInt(); System.out.println("The integer is "+my_val); float my_float = my_scan.nextFloat(); System.out.println("The float value is "+my_float); } }
Kết quả
The string is Joe The integer is 56 The float value is 78.99
Lớp Demo chứa main. Thể hiện Scanner tạo, nextLine đọc từng dòng chuỗi. Integer đọc từ console bằng nextInt. Tương tự nextFloat đọc float. Chúng hiển thị trên console.
Ví dụ 2: BufferedReader
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class Demo{ public static void main(String[] args) throws IOException{ BufferedReader my_reader = new BufferedReader(new InputStreamReader(System.in)); String my_name = my_reader.readLine(); System.out.println("The name is "); System.out.println(my_name); } }
Kết quả
The name is Joe
Lớp Demo chứa main. Thể hiện BufferedReader tạo. Kiểu string định nghĩa và đọc từng dòng bằng readLine. Đầu vào từ standard input, thông báo hiển thị trên console.