Scanner: อ่านหลายค่าในบรรทัดเดียวได้
Scanner ใช้ whitespace (space, tab, newline) เป็น delimiter แยก token อัตโนมัติ
ตัวอย่าง
import java.util.Scanner;
public class Demo {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter two values (float int): ");
// อ่านทีละ token ไม่สนใจว่าอยู่บรรทัดเดียวหรือหลายบรรทัด
double doubleVal = sc.nextDouble(); // nextFloat() ก็ได้
int intVal = sc.nextInt();
System.out.println("Double: " + doubleVal + ", Int: " + intVal);
// อ่านบรรทัดเต็ม (รวม space)
System.out.print("Enter full line: ");
sc.nextLine(); // consume leftover newline
String line = sc.nextLine();
System.out.println("Line: " + line);
}
}
Input/Output ตัวอย่าง
Enter two values (float int): 56.789 99 Double: 56.789, Int: 99 Enter full line: Hello World Line: Hello World
จุดสำคัญ: nextLine() หลัง nextInt()/nextDouble()
nextInt() อ่านแค่ตัวเลข ทิ้ง newline (\n) ไว้ใน buffer
nextLine() ต่อมาจะอ่าน newline ที่เหลือ → ได้ empty string
แก้: ใส่ sc.nextLine(); ดูด newline ทิ้ง ก่อนอ่านบรรทัดจริง
Delimiters อื่นๆ
// ใช้ comma เป็น delimiter
sc.useDelimiter(","); // หรือ regex: sc.useDelimiter("\\s*,\\s*");
String a = sc.next(); // "hello"
String b = sc.next(); // "world"
Java 5+ Console Class (Alternative)
Console console = System.console();
if (console != null) {
String input = console.readLine("Enter: ");
}
ไม่ทำงานใน IDE บางตัว (Eclipse) ใช้ Scanner ปลอดภัยกว่า