是否可以在Java中以字符串形式存储布尔值
我试图存储是否可以在Java中以字符串形式存储布尔值,java,string,boolean,Java,String,Boolean,我试图存储m.find()的布尔值,结果是真的。当它为真时,我希望我的程序打印“成功”。如何使用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());
m.find()
的布尔值,结果是真的。当它为真时,我希望我的程序打印“成功”。如何使用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");
}
是的,但最好将
布尔值存储为布尔值
if (m.find()) {
System.out.println("Successful");
}
或
或
但是您的模式将只匹配一次,因此您只能调用find()
一次。为什么要尝试将m.find
(即布尔值
)的结果分配给字符串
,然后解释为布尔值
?只要如果(m.find()){…}
。在布尔值==true
中,比较是完全多余的。省去它。我如何用if语句检查布尔值是否为真?
-呃,我不想粗鲁,但也许你需要温习一下基本知识…@OliverCharlesworth这是我首先做的。但它不起作用。程序停止了,然后你又做错了什么。请使用该代码更新您的问题,以便我们可以帮助您。请确保您没有调用find()
两次(如上所述)。您的输入只与模式匹配一次。
String answer = Boolean.toString(m.find());
if(answer.equals("true")){
System.out.println("Successful");
}
String answer = m.find() ? "Successful" : "Unsuccessful";
System.out.println(answer);