refactor: simplify ParseInteger (#4376)

This commit is contained in:
Piotr Idzik 2023-09-16 20:57:03 +02:00 committed by GitHub
parent 5bb54977fe
commit 58c21c5756
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 38 additions and 12 deletions

View File

@ -1,6 +1,28 @@
package com.thealgorithms.maths;
public class ParseInteger {
public final class ParseInteger {
private ParseInteger() {
}
private static void checkInput(final String s) {
if (s == null) {
throw new NumberFormatException("Input parameter must not be null!");
}
if (s.isEmpty()) {
throw new NumberFormatException("Input parameter must not be empty!");
}
}
private static void checkDigitAt(final String s, final int pos) {
if (!Character.isDigit(s.charAt(pos))) {
throw new NumberFormatException("Input parameter of incorrect format: " + s);
}
}
private static int digitToInt(final char digit) {
return digit - '0';
}
/**
* Parse a string to integer
*
@ -9,18 +31,15 @@ public class ParseInteger {
* @throws NumberFormatException if the {@code string} does not contain a
* parsable integer.
*/
public static int parseInt(String s) {
if (s == null || s.length() == 0) {
throw new NumberFormatException("Input parameter must not be null!");
}
boolean isNegative = s.charAt(0) == '-';
boolean isPositive = s.charAt(0) == '+';
public static int parseInt(final String s) {
checkInput(s);
final boolean isNegative = s.charAt(0) == '-';
final boolean isPositive = s.charAt(0) == '+';
int number = 0;
for (int i = isNegative ? 1 : isPositive ? 1 : 0, length = s.length(); i < length; ++i) {
if (!Character.isDigit(s.charAt(i))) {
throw new NumberFormatException("Input parameter of incorrect format: " + s);
}
number = number * 10 + s.charAt(i) - '0';
for (int i = isNegative || isPositive ? 1 : 0, length = s.length(); i < length; ++i) {
checkDigitAt(s, i);
number = number * 10 + digitToInt(s.charAt(i));
}
return isNegative ? -number : number;
}

View File

@ -8,6 +8,7 @@ import org.junit.jupiter.api.Test;
*/
public class ParseIntegerTest {
private static final String NULL_PARAMETER_MESSAGE = "Input parameter must not be null!";
private static final String EMPTY_PARAMETER_MESSAGE = "Input parameter must not be empty!";
private static final String INCORRECT_FORMAT_MESSAGE = "Input parameter of incorrect format";
@Test
@ -16,6 +17,12 @@ public class ParseIntegerTest {
Assertions.assertEquals(exception.getMessage(), NULL_PARAMETER_MESSAGE);
}
@Test
public void testEmptyInput() {
IllegalArgumentException exception = Assertions.assertThrows(IllegalArgumentException.class, () -> ParseInteger.parseInt(""));
Assertions.assertEquals(exception.getMessage(), EMPTY_PARAMETER_MESSAGE);
}
@Test
public void testInputOfIncorrectFormat() {
IllegalArgumentException exception = Assertions.assertThrows(NumberFormatException.class, () -> ParseInteger.parseInt("+0a123"));