是否可以将布尔值存储在 Java 中的字符串中
Is it possible to store a boolean in a String in Java
我正在尝试存储 m.find()
的布尔值,结果为真。我希望我的程序在 "Successful"
为真时打印它。如何使用 if
语句检查布尔值是否为真?我该怎么做,因为我不能像示例代码中那样在字符串答案中存储布尔值?
这是我目前的情况。
Pattern p = Pattern.compile("(0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]");
Matcher m = p.matcher("22:30");
System.out.println(m.find());
String answer = m.find();
if(answer==true){
System.out.println("Successful");
}
更新
public static void main(String[] args){
Pattern p = Pattern.compile("(0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]");
Matcher m = p.matcher("22:30");
System.out.println(m.find());
if(m.find()){
System.out.println("Successful");
}
是的,但最好将 boolean
存储为 boolean
。
if (m.find()) {
System.out.println("Successful");
}
或
String answer = Boolean.toString(m.find());
if(answer.equals("true")){
System.out.println("Successful");
}
或
String answer = m.find() ? "Successful" : "Unsuccessful";
System.out.println(answer);
但是你的模式只会匹配一次,所以你只能调用find()
一次。
我正在尝试存储 m.find()
的布尔值,结果为真。我希望我的程序在 "Successful"
为真时打印它。如何使用 if
语句检查布尔值是否为真?我该怎么做,因为我不能像示例代码中那样在字符串答案中存储布尔值?
这是我目前的情况。
Pattern p = Pattern.compile("(0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]");
Matcher m = p.matcher("22:30");
System.out.println(m.find());
String answer = m.find();
if(answer==true){
System.out.println("Successful");
}
更新
public static void main(String[] args){
Pattern p = Pattern.compile("(0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]");
Matcher m = p.matcher("22:30");
System.out.println(m.find());
if(m.find()){
System.out.println("Successful");
}
是的,但最好将 boolean
存储为 boolean
。
if (m.find()) {
System.out.println("Successful");
}
或
String answer = Boolean.toString(m.find());
if(answer.equals("true")){
System.out.println("Successful");
}
或
String answer = m.find() ? "Successful" : "Unsuccessful";
System.out.println(answer);
但是你的模式只会匹配一次,所以你只能调用find()
一次。