ในบทความนี้ เราจะเรียนรู้วิธีรับข้อมูลจากผู้ใช้ในภาษา Java โดยใช้คลาส Scanner
เมธอดหลักของ Scanner
| เมธอด | คืนค่า | คำอธิบาย |
|---|---|---|
| next() | String | อ่านคำเดียว (จนถึง space) |
| nextLine() | String | อ่านบรรทัดเต็ม (รวม space) |
| nextInt() | int | อ่านจำนวนเต็ม |
| nextDouble() | double | อ่านทศนิยม |
| nextBoolean() | boolean | อ่าน true/false |
ตัวอย่างการทำงาน
อินพุต:
Hello, I am John!
เอาต์พุต:
The input string is: Hello, I am John!
อัลกอริทึม
- เริ่มต้นโปรแกรม
- ประกาศตัวแปร String:
value - สร้าง Scanner object
- พรอมป์ผู้ใช้กรอกข้อมูล
- อ่านค่าด้วย
nextLine() - แสดงผลลัพธ์
- จบโปรแกรม
ตัวอย่างที่ 1: ใช้ Scanner (แนะนำ)
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);
}
}
ตัวอย่างที่ 2: ใช้ BufferedReader (แบบเก่า)
import java.io.*;
public class ReadNumber {
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);
}
}
ข้อแตกต่าง
- Scanner: ใช้ง่าย มีเมธอดมาก รองรับทุกชนิดข้อมูล
- BufferedReader: เร็วกว่าสำหรับอ่านไฟล์ขนาดใหญ่ แต่ต้อง parse เอง
- ในปัจจุบันแนะนำใช้ Scanner สำหรับโปรแกรมทั่วไป