Groovy 方法错误 mod 或 %

Groovy error with method mod or %

我刚开始在 Groovy 编程,我遇到了这个错误,我想看看是否有人可以帮助我解决这个问题。

java.lang.UnsupportedOperationException: Cannot use mod() on this number type: java.math.BigDecimal with value: 5
    at Script1.hailstone(Script1.groovy:8)
    at Script1$hailstone.callCurrent(Unknown Source)
    at Script1.hailstone(Script1.groovy:11)
    at Script1$hailstone.callCurrent(Unknown Source)
    at Script1.hailstone(Script1.groovy:14)
    at Script1$_run_closure1.doCall(Script1.groovy:1)
    at Script1.run(Script1.groovy:1)

我有以下 Groovy 代码

def list = [1,2,3].findAll{it-> hailstone(it)}

def hailstone(num){
    if(num==1){
        return 1;
    }
    println num
    println num.mod(2)
    if(num.mod(2)==0){
        num = num/2;
        return 1 + hailstone(num)
    }else{
        num = 3*num + 1
        return 1 + hailstone(num)
    }
}

和输出:

2
0
3
1 
10
0
5

然后它突然在 5.mod(2) 上抛出错误。

提前致谢。

看起来 'num' 在您点击该行时被强制转换为 BigDecimal num = num/2

如果将冰雹方法的签名更改为: def hailstone(int num) 它不会崩溃(因为参数会在每次调用时被强制转换为 int),但这可能不会给出您想要的结果,因为您会失去精度,例如当 'num' 为奇数且 num/2 为小数时,该值将被截断。

有关 Groovy 数学运算的(有时令人惊讶的)方式的更多信息,请查看 http://groovy.codehaus.org/Groovy+Math

在 运行 这段代码之后,由于 findAll,它没有产生正确的输出。这是经过一些小调整的代码:

def list = [1,2,3].collect { hailstone(it) }  // use collect, no need for the "it ->" variable it is implicit.

 def hailstone(int num) {      // int data type to prevent BigDecimal from being passed to mod()
   if (num == 1) {
     return 1                  // no need for semi-colons in groovy
   } else if (num % 2 == 0) {  // use modulus operator 
     num = num / 2
   } else {
     num = 3 * num + 1
   }

   return 1 + hailstone(num)   // this line happens regardless of the condition in the else if or the else
 }

 println list  // outputs : [1,2,8]