Check if a number is positive or negative in Java (#12604)
* Check if a number is positive or negative in Java * reformat single line if/else statements * Check if a number is positive or negative in Java
This commit is contained in:
parent
3f1f6bd34b
commit
842a71ad92
@ -0,0 +1,38 @@
|
|||||||
|
package com.baeldung.positivenegative;
|
||||||
|
|
||||||
|
public class PositiveOrNegative {
|
||||||
|
enum Result {
|
||||||
|
POSITIVE, NEGATIVE, ZERO
|
||||||
|
}
|
||||||
|
|
||||||
|
public static Result byOperator(Integer integer) {
|
||||||
|
if (integer > 0) {
|
||||||
|
return Result.POSITIVE;
|
||||||
|
} else if (integer < 0) {
|
||||||
|
return Result.NEGATIVE;
|
||||||
|
}
|
||||||
|
return Result.ZERO;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static Result bySignum(Integer integer) {
|
||||||
|
int result = Integer.signum(integer);
|
||||||
|
|
||||||
|
if (result == 1) {
|
||||||
|
return Result.POSITIVE;
|
||||||
|
} else if (result == -1) {
|
||||||
|
return Result.NEGATIVE;
|
||||||
|
}
|
||||||
|
return Result.ZERO;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static Result bySignum(Float floatNumber) {
|
||||||
|
float result = Math.signum(floatNumber);
|
||||||
|
|
||||||
|
if (result == 1.0f) {
|
||||||
|
return Result.POSITIVE;
|
||||||
|
} else if (result == -1.0f) {
|
||||||
|
return Result.NEGATIVE;
|
||||||
|
}
|
||||||
|
return Result.ZERO;
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,29 @@
|
|||||||
|
package com.baeldung.positivenegative;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
import static com.baeldung.positivenegative.PositiveOrNegative.Result.*;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
|
||||||
|
class PositiveOrNegativeUnitTest {
|
||||||
|
@Test
|
||||||
|
void givenIntegers_whenChkPositiveOrNegativeByOperator_thenReturnExpectedResult() {
|
||||||
|
assertEquals(POSITIVE, PositiveOrNegative.byOperator(42));
|
||||||
|
assertEquals(ZERO, PositiveOrNegative.byOperator(0));
|
||||||
|
assertEquals(NEGATIVE, PositiveOrNegative.byOperator(-700));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void givenIntegers_whenChkPositiveOrNegativeBySignum_thenReturnExpectedResult() {
|
||||||
|
assertEquals(POSITIVE, PositiveOrNegative.bySignum(42));
|
||||||
|
assertEquals(ZERO, PositiveOrNegative.bySignum(0));
|
||||||
|
assertEquals(NEGATIVE, PositiveOrNegative.bySignum(-700));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void givenFloats_whenChkPositiveOrNegativeBySignum_thenReturnExpectedResult() {
|
||||||
|
assertEquals(POSITIVE, PositiveOrNegative.bySignum(4.2f));
|
||||||
|
assertEquals(ZERO, PositiveOrNegative.bySignum(0f));
|
||||||
|
assertEquals(NEGATIVE, PositiveOrNegative.bySignum(-7.7f));
|
||||||
|
}
|
||||||
|
}
|
Loading…
x
Reference in New Issue
Block a user