Last active
August 15, 2016 19:38
-
-
Save jeyemwey/28d4100dba0b0678325c5e6c1cb45884 to your computer and use it in GitHub Desktop.
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
import java.util.HashMap; | |
public class CustomStringToInt { | |
/** | |
* Initialize the HashMap with the decimal numbers. | |
* | |
* @return The initialized HashMap. | |
*/ | |
private static HashMap<Character, Integer> initCharToIntMap() { | |
HashMap<Character, Integer> chars = new HashMap<Character, Integer>(); | |
chars.put('0', 0); chars.put('1', 1); | |
chars.put('2', 2); chars.put('3', 3); | |
chars.put('4', 4); chars.put('5', 5); | |
chars.put('6', 6); chars.put('7', 7); | |
chars.put('8', 8); chars.put('9', 9); | |
return chars; | |
} | |
/** | |
* @var chars The HashMap that was created in initCharToIntMap() | |
*/ | |
private static HashMap<Character, Integer> chars = initCharToIntMap(); | |
/** | |
* Gets the int for this character. It is outsourced from the convert() | |
* method to catch java.lang.NullPointerException|s that might occur when | |
* requesting not mapped characters (e.g. in "12b3", b will return -1). | |
* Although removeNonDigits() should have thrown them out, I guess it's kind | |
* of good habit to catch this thing. | |
* | |
* @param key The "requested" character. | |
* @return The int for character or -1 if character is not mapped. | |
*/ | |
private static int getIntForChar(char key) { | |
try { | |
return chars.get(key); | |
} catch (NullPointerException e) { | |
return -1; | |
} | |
} | |
/** | |
* Remove all non-digit characters from the string set. | |
* | |
* @param in The raw string. | |
* @return A string with digits only. | |
*/ | |
private static String removeNonDigits(String in) { | |
return in.replaceAll("[^\\d.]", ""); | |
} | |
/** | |
* The callable Method which does the magic. | |
* | |
* @param in The String that comes in. | |
* @return The unsigned integer that will come back. | |
*/ | |
public static int convert(String in) { | |
in = removeNonDigits(in); | |
System.out.println(in); | |
int result = 0; | |
int exp = in.length() - 1; | |
for(int i = 0; i < in.length(); i++) { | |
int num = getIntForChar(in.charAt(i)); | |
if(num < 0) { | |
continue; | |
} | |
result += num * Math.pow(10, exp); | |
exp -= 1; | |
} | |
return result; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment