Last active
August 29, 2015 14:09
-
-
Save bluerogue/71e98406e8748f96131f to your computer and use it in GitHub Desktop.
String to Integer without needing exception handling
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* Copyright (C) 2014 Matthew Roberts | |
* MIT License, http://opensource.org/licenses/MIT | |
*/ | |
import java.util.regex.Matcher; | |
import java.util.regex.Pattern; | |
/** | |
* Checks to see if a String can be used as a valid Integer without resorting to | |
* exception handling. | |
* | |
* @author mroberts | |
*/ | |
public class StringToIntegerValidator { | |
private static final String INTEGER_PATTERN = "(-)?(\\d){1,19}$"; | |
public boolean isInteger(String stringNumber) { | |
boolean isInteger = false; | |
Pattern pattern = Pattern.compile(INTEGER_PATTERN, | |
Pattern.CASE_INSENSITIVE); | |
Matcher matcher = pattern.matcher(stringNumber); | |
if (matcher.matches()) { | |
long longNumber = Long.parseLong(stringNumber); | |
if (longNumber <= Integer.MAX_VALUE && longNumber >= Integer.MIN_VALUE) { | |
isInteger = true; | |
} | |
} | |
return isInteger; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* Copyright (C) 2014 Matthew Roberts | |
* MIT License, http://opensource.org/licenses/MIT | |
*/ | |
public class StringToIntegerValidatorTest extends TestCase { | |
@Test | |
public void validIntegerTest() { | |
StringToIntegerValidator validator = new StringToIntegerValidator(); | |
Boolean isValidInteger = null; | |
isValidInteger = validator.isInteger("2147483647"); | |
assertTrue(isValidInteger.equals(true)); | |
isValidInteger = validator.isInteger("-42"); | |
assertTrue(isValidInteger.equals(true)); | |
isValidInteger = validator.isInteger("0"); | |
assertTrue(isValidInteger.equals(true)); | |
} | |
@Test | |
public void invalidIntegerTest() { | |
StringToIntegerValidator validator = new StringToIntegerValidator(); | |
Boolean isValidInteger = null; | |
isValidInteger = validator.isInteger("Not an int."); | |
assertTrue(isValidInteger.equals(false)); | |
isValidInteger = validator.isInteger("123045678.5"); | |
assertTrue(isValidInteger.equals(false)); | |
isValidInteger = validator.isInteger("123456789123456789"); | |
assertTrue(isValidInteger.equals(false)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment