Modulus of Negative Numbers in Java (#14640)

This commit is contained in:
Michael Olayemi 2023-08-26 04:28:13 +01:00 committed by GitHub
parent a188c57987
commit d7c57a2e2b
1 changed files with 67 additions and 44 deletions

View File

@ -1,5 +1,7 @@
package com.baeldung.modulo;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import static org.assertj.core.api.Java6Assertions.*;
@ -40,6 +42,27 @@ public class ModuloUnitTest {
assertThat(4 % 2).isEqualTo(0);
}
@Test
public void whenDividendIsNegativeAndModulusIs2_thenResultIsNegative() {
assertEquals(-1, -9 % 2);
}
@Test
public void whenDividendIsNegativeAndRemainderIsCheckedForNegativeValue_thenResultIsPositive() {
int remainder = -9 % 2;
if (remainder < 0) {
remainder += 2;
}
assertEquals(1, remainder);
}
@Test
public void whenDividendIsNegativeAndUsesMathClass_thenResultIsPositive() {
int remainder = Math.floorMod(-9, 2);
assertEquals(1, remainder);
}
@Test
public void whenItemsIsAddedToCircularQueue_thenNoArrayIndexOutOfBounds() {
int QUEUE_CAPACITY = 10;