dimanche 1 mars 2015

Converting String to values in hashmap

I'm working on a program that reads in a string and then converts each character of that string into a number based on its value in the hashmap.


Just like a telephone number. What I'm having trouble with is the logic behind it, I can't seem to get it work.


What I'm doing is converting the string to a char array and then iterating over it and grabbing the first character. Then I find the key in the hashmap corresponding to the letter and get the value of it. I add this value to my empty word (this will build up the new string).


Can't seem to get it to work, been working on it for a while. Thanks for help.


Hashmap values: mapped as



public static void setUpHashmap(){
lettersToNumbers.put("abc", '2');
lettersToNumbers.put("def", '3');
lettersToNumbers.put("ghi", '4');
lettersToNumbers.put("jkl", '5');
lettersToNumbers.put("mno", '6');
lettersToNumbers.put("pqrs", '7');
lettersToNumbers.put("tuv", '8');
lettersToNumbers.put("wxyz", '9');
}


Code:



public static String convertCharStringToNumbers(String str){
char[] stringArray = str.toCharArray();
String word = "";
for (int i = 0; i < stringArray.length; i++){
char letter = stringArray[i];
if (lettersToNumbers.containsKey(letter)){
word+=lettersToNumbers.get(letter);
}
}
System.out.println(word.toString());
return word;

}

Aucun commentaire:

Enregistrer un commentaire