From 90a3792ccc7909fa9a54412f3f48dc02efe093e0 Mon Sep 17 00:00:00 2001 From: Patrick Gotthard Date: Fri, 18 Apr 2014 19:28:04 +0200 Subject: [PATCH] Added method to parse Integers --- .../java/com/rometools/utils/Integers.java | 22 ++++++++++++++++ .../com/rometools/utils/IntegersTest.java | 26 +++++++++++++++++++ 2 files changed, 48 insertions(+) create mode 100644 src/main/java/com/rometools/utils/Integers.java create mode 100644 src/test/java/com/rometools/utils/IntegersTest.java diff --git a/src/main/java/com/rometools/utils/Integers.java b/src/main/java/com/rometools/utils/Integers.java new file mode 100644 index 0000000..ec5ca85 --- /dev/null +++ b/src/main/java/com/rometools/utils/Integers.java @@ -0,0 +1,22 @@ +package com.rometools.utils; + +public final class Integers { + + private Integers() { + } + + /** + * Converts a String into an Integer. + * + * @param s The String to convert, may be null + * @return The parsed Integer or null when parsing is not possible + */ + public static Integer parse(final String s) { + try { + return Integer.parseInt(s); + } catch (final NumberFormatException e) { + return null; + } + } + +} diff --git a/src/test/java/com/rometools/utils/IntegersTest.java b/src/test/java/com/rometools/utils/IntegersTest.java new file mode 100644 index 0000000..8fc40db --- /dev/null +++ b/src/test/java/com/rometools/utils/IntegersTest.java @@ -0,0 +1,26 @@ +package com.rometools.utils; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.nullValue; + +import org.junit.Test; + +public class IntegersTest { + + @Test + public void testParse() { + + final String nullString = null; + final String emptyString = null; + final String integerString = "1"; + final String decimalString = "1.0"; + + assertThat(Integers.parse(nullString), is(nullValue())); + assertThat(Integers.parse(emptyString), is(nullValue())); + assertThat(Integers.parse(integerString), is(1)); + assertThat(Integers.parse(decimalString), is(nullValue())); + + } + +}