如何在Java中检查字符串值是否为布尔类型?
lang 包的 Boolean 类提供两种方法,即 parseBoolean() 和 valueOf()。
parseBoolean(String s) − 此方法接受一个字符串变量并返回布尔值。如果给定的字符串值为 "true"(不区分大小写),则此方法返回 true;否则,如果它为 null、false 或任何其他值,则返回 false。
valueOf(String s) − 此方法接受一个字符串值,对其进行解析,并根据给定的值返回 Boolean 类的对象。您可以使用此方法代替构造函数。如果给定的字符串值为 "true",则此方法返回 true;否则,返回 false。
示例
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 result = Boolean.parseBoolean(str);
System.out.println(result);
boolean result2 = Boolean.valueOf(str);
System.out.println(result2);
}
}输出1
Enter a string value: true true true
输出2
Enter a string value: false false false
但是,这些方法都不能验证给定字符串的值是否为“true”。没有可用的方法来验证字符串的值是否为布尔类型。您需要使用 if 循环或正则表达式直接进行验证。
示例:使用 if 循环
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(); 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");
}
}
}输出1
Enter a string value: true Given string is a boolean type
输出2
Enter a string value: false Given string is a boolean type
输出3
Enter a string value: hello Given string is not a boolean type
示例:使用正则表达式
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
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();
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");
}
}
}输出1
Enter a string value: true Given string is a boolean type
输出2
Enter a string value: false Given string is a boolean type
输出3
Enter a string value: hello Given string is not a boolean type
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP