Groovy整数除法运算符使用及Java迁移条件判断异常解决
Hey there! I’ve run into these exact Groovy gotchas when migrating Java code too—let’s fix them up for you:
1. Groovy里的整数除法怎么处理?
Groovy and Java have a key difference in how the / operator works:
- In Java, when you divide two integers with
/, it performs integer division (truncating the decimal part to keep only the integer quotient). - But in Groovy, regardless of whether the operands are integers,
/will always return a floating-point result by default.
To get the same integer division behavior as Java, you have a few solid options:
- Use Groovy's built-in
intdiv()method (most recommended for broad compatibility):// 301.intdiv(100) returns 3, matching Java's 301/100 result status_num.intdiv(100) - Cast the division result to an integer explicitly:
(status_num / 100) as int - If you're using Groovy 3.0 or later, you can also use the
//integer division operator:status_num // 100
2. Why does your if condition return false in Groovy?
This is directly caused by the division behavior difference we just covered!
In Java, 301 / 100 is integer division that results in 3, so 3 == 3 evaluates to true.
In Groovy, though, 301 / 100 returns the float 3.01, and 3.01 == 3 is obviously false.
Switching to an integer division method will make your condition behave exactly like it did in Java. Here's your fixed code:
int status_num = 301 if (status_num.intdiv(100) == 3) { throw new GoogleServiceConditionException("Google Search System is under maintenance") }
内容的提问来源于stack exchange,提问作者SkyWalker
相关产品推荐
相关产品推荐

