java 0%2==0,`的java(0%2!= 0)== FALSE`

The part I keep getting stuck on is

boolean(0 % 2 !=0)

== false. I mean if 2 goes into 0, 0 times then the remainder would be 2, and 2 does not equal 0. So it should be true. Yet but when I put the boolean in my java program it is treating it as false. Anyone know why?

The only logical answer I can wrap my head around is that maybe integers go into 0 and infinite number of times and so are recognized as false, anyone?

解决方案

There are two steps:

0 % 2 evaluates to 0.

0 != 0 evaluates to false.

To elaborate on the first step, the JLS defines the % operator like so:

The binary % operator is said to yield the remainder of its operands from an implied division; the left-hand operand is the dividend and the right-hand operand is the divisor.

The remainder of dividing 0 by 2 is 0 and not 2 as you seem to think.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
下面是NumberUtil类的实现和对应的JUnit单元测试用例: NumberUtil.java ``` public class NumberUtil { /*判断输入的数字是否为素数*/ public Boolean isPrime(int num){ if(num < 2) { return false; } for(int i=2; i<=Math.sqrt(num); i++){ if(num % i == 0) { return false; } } return true; } /*判断输入的数字是否满足能被7或9整除但不能被2或5整除*/ public boolean isDivisible(int num){ if(((num % 7 == 0) || (num % 9 == 0)) && (num % 5 != 0 && num % 2 != 0)){ return true; } else { return false; } } } ``` NumberUtilTest.java ``` import static org.junit.Assert.*; import org.junit.Test; public class NumberUtilTest { @Test public void testIsPrime() { NumberUtil util = new NumberUtil(); assertTrue(util.isPrime(2)); assertTrue(util.isPrime(3)); assertTrue(util.isPrime(5)); assertTrue(util.isPrime(7)); assertTrue(util.isPrime(11)); assertTrue(util.isPrime(13)); assertFalse(util.isPrime(1)); assertFalse(util.isPrime(4)); assertFalse(util.isPrime(6)); assertFalse(util.isPrime(8)); assertFalse(util.isPrime(9)); assertFalse(util.isPrime(10)); assertFalse(util.isPrime(12)); assertFalse(util.isPrime(14)); } @Test public void testIsDivisible() { NumberUtil util = new NumberUtil(); assertTrue(util.isDivisible(7)); assertTrue(util.isDivisible(9)); assertTrue(util.isDivisible(14)); assertTrue(util.isDivisible(18)); assertTrue(util.isDivisible(21)); assertFalse(util.isDivisible(2)); assertFalse(util.isDivisible(5)); assertFalse(util.isDivisible(10)); assertFalse(util.isDivisible(15)); assertFalse(util.isDivisible(20)); } } ``` 注意:在判断素数时,需要注意num小于2的情况;在判断是否满足能被7或9整除但不能被2或5整除时,需要注意括号的使用。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值