What's wrong with groovy math?
This seems quite bizarre to me and totally putting me on the side of people willing to use plain jav开发者_运维知识库a. While writing a groovy based app I encountered such thing:
int filesDaily1 = (item.filesDaily ==~ /^[0-9]+$/) ?
Integer.parseInt(item.filesDaily) : item.filesDaily.substring(0, item.filesDaily.indexOf('.'))
def filesDaily = (item.filesDaily ==~ /^[0-9]+$/) ?
Integer.parseInt(item.filesDaily) : item.filesDaily.substring(0, item.filesDaily.indexOf('.'))
So, knowing that item.filesDaily is a String with value '1..*' how can it possibly be, that filesDaily1 is equal to 49 and filesDaily is equal to 1?
What's more is that when trying to do something like
int numOfExpectedEntries = filesDaily * item.daysToCheck
an exception is thrown saying that
Cannot cast object '111' with class 'java.lang.String' to class 'int'
pointing to that exact line of code with multiplication. How can that happen?
You're assigning this value to an int:
item.filesDaily.substring(0, item.filesDaily.indexOf('.'))
I'm guessing that Groovy is converting the single-character string "1" into the char '1' and then taking the Unicode value in the normal char-to-int conversion... so you end up with the value 49.
If you want to parse a string as a decimal number, use Integer.parseInt
instead of a built-in conversion.
The difference between filesDaily1
and filesDaily
here is that you've told Groovy that filesDaily1
is meant to be an int, so it's applying a conversion to int. I suspect that filesDaily
is actually the string "1" in your test case.
I suspect you really just want to change the code to something like:
String text = (item.filesDaily ==~ /^[0-9]+$/) ? items.filesDaily :
item.filesDaily.substring(0, item.filesDaily.indexOf('.'))
Integer filesDaily = text.toInteger()
This is a bug in the groovy type conversion code.
int a = '1'
int b = '11'
return different results because different converters are used. In the example a
will be 49 while b
will be 11. Why?
The single-character-to-int conversion (using String.charAt(0)
) has a higher precedence than the integer parser.
The bad news is that this happens for all single character strings. You can even do int a = 'A'
which gives you 65.
As long as you have no way of knowing how long the string is, you must use Integer.parseInt()
instead of relying on the automatic type conversion.
精彩评论