คลาส Boolean มีเมธอดสองตัวสำหรับแปลงสตริงเป็น boolean:
- parseBoolean(String s) - คืนค่า true ถ้าสตริงคือ "true" (ไม่สนใจ case) มิฉะนั้น false (รวม null, "false", ค่าอื่นๆ)
- valueOf(String s) - คืนค่า Boolean object แบบเดียวกันกับ parseBoolean
ตัวอย่างพื้นฐาน
import java.util.Scanner;
public class VerifyBoolean {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter a string value: ");
String str = sc.next();
boolean result1 = Boolean.parseBoolean(str);
boolean result2 = Boolean.valueOf(str);
System.out.println("parseBoolean: " + result1);
System.out.println("valueOf: " + result2);
}
}
ผลลัพธ์
Enter a string value: true
parseBoolean: true
valueOf: true
Enter a string value: false
parseBoolean: false
valueOf: false
Enter a string value: hello
parseBoolean: false
valueOf: false
ปัญหา: ไม่สามารถแยก "false" กับค่าผิดพลาดได้
ทั้งสองเมธอดคืนค่า false สำหรับ "false", "hello", null, "" - ไม่บอกว่าเป็น boolean จริงหรือแค่ค่าที่แปลงไม่ได้
วิธีแก้: ตรวจสอบแบบตรงไปตรงมา
วิธีที่ 1: ใช้ if + equalsIgnoreCase
if (str.equalsIgnoreCase("true") || str.equalsIgnoreCase("false")) {
System.out.println("Given string is a boolean type");
} else {
System.out.println("Given string is not a boolean type");
}
วิธีที่ 2: ใช้ Regular Expression
import java.util.regex.*;
Pattern pattern = Pattern.compile("true|false", Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(str);
if (matcher.matches()) {
System.out.println("Given string is a boolean type");
} else {
System.out.println("Given string is not a boolean type");
}
ผลลัพธ์ทั้งสองวิธี
Enter a string value: true
Given string is a boolean type
Enter a string value: false
Given string is a boolean type
Enter a string value: hello
Given string is not a boolean type
สรุป
| เมธอด | ใช้สำหรับ | ข้อจำกัด |
|---|---|---|
| Boolean.parseBoolean() | แปลงเป็น boolean เพื่อใช้งาน | ไม่แยก "false" กับ invalid input |
| Boolean.valueOf() | แปลงเป็น Boolean object | เหมือนด้านบน |
| equalsIgnoreCase + OR | ตรวจสอบว่าเป็น boolean string จริง | ง่าย เร็ว |
| Regex matches() | ตรวจสอบรูปแบบ | ยืดหยุ่นกว่า |