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!