Groovy error with mod or% method

I just started programming in Groovy, I have this error, and I wanted to see if anyone could help me with this.

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)

I have the following Groovy code

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

and conclusion:

2
0
3
1 
10
0
5

and then it unexpectedly causes an error on 5.mod (2).

Thanks in advance.

+4
source share
2 answers

Looks like 'num' gets forced into BigDecimal when you click on a string num = num/2

: def hailstone(int num) ( int ), , , . "num" , num/2 , .

( ) Groovy . http://groovy.codehaus.org/Groovy+Math

+3

- 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]
0

All Articles