user12824107
user12824107

Reputation:

Catching error conditions in Java Hashmap

In an earlier question I was given some guidance on how to map characters to numbers. In the code below I can use the Hashmap to attribute the number "2" to "a".

Integer number = characters.get(ch[r]);

Map<Character, Integer> characters = new HashMap<>();
characters.put('a', 2);
characters.put('b', 2);
characters.put('c', 2);
characters.put('d', 3);
characters.put('e', 3);
characters.put('f', 3);

Is it possible to code a catch all for the Hashmap so if say the character Z was entered I can catch this without the code crashing. Basically I want to be able to code that if any character other than a-f is entered I can catch before crash.

Upvotes: 0

Views: 235

Answers (2)

Hassam Abdelillah
Hassam Abdelillah

Reputation: 2304

There is a Java 8 feature to handle such cases :

characters.getOrDefault("Z", -1);

the value -1 would represents unknown charcters not existing in your map.

Upvotes: 2

Mureinik
Mureinik

Reputation: 311393

You could use the getOrDefault method to get a default value for any value that isn't between a and f:

Integer number = characters.getOrDefault(userInput, 0 /* or some other default */);

Upvotes: 3

Related Questions