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,54 +1,77 @@
package com.baeldung.modulo;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import static org.assertj.core.api.Java6Assertions.*;
public class ModuloUnitTest {
@Test
public void whenIntegerDivision_thenLosesRemainder(){
assertThat(11 / 4).isEqualTo(2);
}
@Test
public void whenDoubleDivision_thenKeepsRemainder(){
assertThat(11 / 4.0).isEqualTo(2.75);
}
@Test
public void whenModulo_thenReturnsRemainder(){
assertThat(11 % 4).isEqualTo(3);
}
@Test(expected = ArithmeticException.class)
public void whenDivisionByZero_thenArithmeticException(){
double result = 1 / 0;
}
@Test(expected = ArithmeticException.class)
public void whenModuloByZero_thenArithmeticException(){
double result = 1 % 0;
}
@Test
public void whenDivisorIsOddAndModulusIs2_thenResultIs1(){
assertThat(3 % 2).isEqualTo(1);
}
@Test
public void whenDivisorIsEvenAndModulusIs2_thenResultIs0(){
assertThat(4 % 2).isEqualTo(0);
}
@Test
public void whenItemsIsAddedToCircularQueue_thenNoArrayIndexOutOfBounds(){
int QUEUE_CAPACITY= 10;
int[] circularQueue = new int[QUEUE_CAPACITY];
int itemsInserted = 0;
for (int value = 0; value < 1000; value++) {
int writeIndex = ++itemsInserted % QUEUE_CAPACITY;
circularQueue[writeIndex] = value;
@Test
public void whenIntegerDivision_thenLosesRemainder() {
assertThat(11 / 4).isEqualTo(2);
}
@Test
public void whenDoubleDivision_thenKeepsRemainder() {
assertThat(11 / 4.0).isEqualTo(2.75);
}
@Test
public void whenModulo_thenReturnsRemainder() {
assertThat(11 % 4).isEqualTo(3);
}
@Test(expected = ArithmeticException.class)
public void whenDivisionByZero_thenArithmeticException() {
double result = 1 / 0;
}
@Test(expected = ArithmeticException.class)
public void whenModuloByZero_thenArithmeticException() {
double result = 1 % 0;
}
@Test
public void whenDivisorIsOddAndModulusIs2_thenResultIs1() {
assertThat(3 % 2).isEqualTo(1);
}
@Test
public void whenDivisorIsEvenAndModulusIs2_thenResultIs0() {
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;
int[] circularQueue = new int[QUEUE_CAPACITY];
int itemsInserted = 0;
for (int value = 0; value < 1000; value++) {
int writeIndex = ++itemsInserted % QUEUE_CAPACITY;
circularQueue[writeIndex] = value;
}
}
}
}