2015-02-09 56 views
-3

我试图存储布尔m.find()出来是真实的。如果它是真的,我希望我的程序打印"Successful"。如何检查布尔值是否为if陈述?我如何做到这一点,因为我不能像字符串答案中存储布尔值,就像我在示例代码中那样?是否有可能存储在Java中的字符串中的布尔值

这是我到目前为止。

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"); 
    }    

UPDATE

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"); 
    } 
+8

你为什么要将'm.find'(它是'boolean')的结果赋值给''String',然后解释为'boolean'?只要'(m.find()){...}'。 – 2015-02-09 23:10:46

+0

在'boolean_value == true'中,比较是完全多余的。离开它。 – Deduplicator 2015-02-09 23:11:32

+4

'我该如何检查boolean是否属于if语句?' - 错,我讨厌粗鲁,但也许你需要重新学习基础知识...... – John3136 2015-02-09 23:12:24

回答

0

是的,但最好是一个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()一次。

+0

@ GladL33他们*全部*在这里工作。 – 2015-02-09 23:29:56

+1

确保你没有调用'find()'两次(就像你在上面)。你的输入只能匹配你的模式*一次*。 – 2015-02-09 23:30:32

相关问题