Groovy条件判断异常:为何始终输出‘it will be stopped’
Groovy条件判断问题分析与修复
你的代码里的if条件写法存在错误,导致不管test的值是什么,条件都会判定为true,所以println语句总是会执行。
问题原因
||是逻辑或运算符,要求左右两侧必须都是布尔表达式。但你写的条件是:
test ==~ "deallocated"||"stopped"
这里右侧的"stopped"是非空字符串,在Groovy中非空字符串会被自动转换为布尔值true。所以整个表达式等价于:
(test ==~ "deallocated") || true
不管左边的正则匹配结果是true还是false,true和任何值做逻辑或运算的结果都是true,因此条件永远成立。
修复方案
根据你的需求,有几种正确的写法:
分别对两个字符串做正则匹配
把逻辑或的两边都写成完整的布尔判断:def test = "started" if (test ==~ "deallocated" || test ==~ "stopped") { println "it will be stopped" }合并正则表达式
如果需要用正则匹配,可以把两个匹配规则合并成一个正则表达式:def test = "started" if (test ==~ /deallocated|stopped/) { println "it will be stopped" }精确匹配字符串(更高效)
如果你只是想判断test是否等于这两个字符串中的一个,用in关键字更简洁高效:def test = "started" if (test in ["deallocated", "stopped"]) { println "it will be stopped" }
内容的提问来源于stack exchange,提问作者WhoAmI
相关产品推荐
相关产品推荐

