如果条件执行,即使它是假的?
def findFdrsWithMaturityYear(year){
def fdrs = Fdr.findAll()
def foundFdrs = new ArrayList<Fdr>()
def foundYear
fdrs.each {
foundYear = DateUtils.getYearFromDate(it.maturityDate)
if (year.toString() == foundYear.toString()){ // line 7
foundFdrs.add(it) // line 8
}
}
return foundFdrs
}
上面是常规代码。我正在用 intellijidea 11 调试它,当我到达第 7 行时,我发现即使条件为 false,它也会转到第 8 行,但 findFdrs 列表不会增长,因为它在列表中添加了一个元素。我在 grails Web 应用程序中使用此代码,每次运行此 Web 应用程序时,即使第 7 行的条件为 true,我也会得到空的foundFdr 列表。我还通过创建 grails 集成测试来测试上面的代码,测试成功通过,即我得到了包含一些元素的 findFdrs 列表,但不在我的 grails 应用程序中,问题出在哪里?
def findFdrsWithMaturityYear(year){
def fdrs = Fdr.findAll()
def foundFdrs = new ArrayList<Fdr>()
def foundYear
fdrs.each {
foundYear = DateUtils.getYearFromDate(it.maturityDate)
if (year.toString() == foundYear.toString()){ // line 7
foundFdrs.add(it) // line 8
}
}
return foundFdrs
}
Above is groovy code. I'm debugging it with intellijidea 11, when I reach at line no 7, I found that even if the condition is false, it goes to line no 8, but foundFdrs list does not grow as it adds one element in the list. I'm using this code in a grails web app, every time I run this web app, I get empty foundFdr list even if condition at line no 7 is true. I also tested above code by creating a grails integration test, test passes successfully, ie I get foundFdrs list with some elements, but not in my grails app, Where is the problem ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我怀疑尽管调试器显示该行正在执行,但它实际上并未执行
也不知道为什么你要在两个变量上执行 toString...
I suspect that despite the debugger showing that line as being executed, it isn't in fact executed
Not sure why you are doing toString on both vars either...
一个安全的选择是简单地使用 StringUtils#equals
因为两个字符串可能会或可能不会使用“==”进行比较
A safe option would be to use simply use StringUtils#equals
as two string may or may not be compared by using "=="
我认为问题出在“if”条件内。你有year.toString()==foundYear.toString(),它本质上是在说“if(string==string)”,但是==运算符可能不会被重载来比较Groovy中的字符串(我真的不知道Groovy,但我用 Java 和 Scala 编程)。查看 Groovy 文档,看看是否有任何用于字符串比较的“equals”方法,因为我非常怀疑 == 运算符是否会执行您想要的操作。希望这会有所帮助!
由于 Groovy 是一种类似 Java 的语言,因此您可能需要查看一下 = http: //www.devdaily.com/java/edu/qanda/pjqa00001.shtml
I would assume the problem lies within the "if" condition. You have year.toString() == foundYear.toString() which is essentially saying "if (string == string)", however the == operator may not be overloaded to compare strings in Groovy (I do not know Groovy really, but I program in Java and Scala). Look through the Groovy documentation and see if there is any "equals" method for string comparison, since I highly doubt that the == operator will do what you were intending. Hope this helps a little bit!
Since Groovy is a Java-like language, you may want to check this out = http://www.devdaily.com/java/edu/qanda/pjqa00001.shtml