0

I have a HashMap set, and I take String input from user using Scanner. I want to take user input string then calculate width of entire message by adding values that they represent in the Hashmap.

So for instance, lets say you enter "test". The value of t in hashmap is 2, the value of e is 3, the value of s is 3, and the value of t is also 2. The values all add up so you end up with 10.

System.out.print("How much width do you want i to have? ");
int i = input.nextInt();

System.out.println("\nEnter the string input:");
Scanner scan = new Scanner(System.in);
String user_input = scan.nextLine();

Map<String,Integer> map = new HashMap<String,Integer>();

            map.put("a", i*2);
            map.put("b", i*2);
            map.put("c", i*2);
            map.put("d", i*2);
            map.put("e", i*3);
            map.put("f", i*2);
            map.put("g", i*2);
            map.put("h", i*2);
            map.put("i", i*1);
...down to z

Just so you know, the values of all of the keys are relative to the value of i so that is why I have the values set to i*n.

I tried:

int count = map.containsKey("a") ? map.get("a") : 0;
map.put("a", count + 1);

but that simply tells me what the value of key 'a' is set to. I would need to run each letter of string through the hashmap, acquire the value, and add each value together. Then get the total sum. I know that would require a for loop to iterate through each letter in the string one at a time. Clearly, I'm missing some important portion in the code.

Also, would it be possible to directly set into hashmap how many of a's exist, how many b's exist, etc? I set a flexible arraylist for that that would let me add/remove letters, but if I can do it in hashmap, it would make things easier.

Thanks!

sega_one
  • 63
  • 3
  • 9
  • Your question starts talking about the sum, and ends asking about the counts (in a not so clear way). You probably need to maps - one for counts and to be used to calculate the sum. – Bhesh Gurung Apr 27 '13 at 21:12
  • Well, if I can get the count of characters in string input, I can calculate the sum by simply adding the key values of each of the characters in string. That is pretty much where i'm at currently trying to figure out the coding portion – sega_one Apr 27 '13 at 21:30
  • It is not clear what your question is here. Please edit your post and ask a clear question or it will be closed. – RBarryYoung Apr 27 '13 at 22:34

1 Answers1

1
int sum = 0;
for(int i = 0; i < user_input.length(); i++) {
    sum += map.get(user_input.charAt(i));
}

You could avoid the iteration of you use functional language like Scala. Or adding some folding capability: link

Community
  • 1
  • 1
Csaba Toth
  • 10,021
  • 5
  • 75
  • 121