Reputation: 1069
Am actually trying to get the hashmap value by using get(Object key)
function.
But the below code is throwing NullPointerException
at line
count+=hm.get((int)str.charAt(i));
So please help me to fix it.
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String str = String.valueOf(br.readLine());
HashMap<Integer,Integer> hm =new HashMap<Integer,Integer>();
hm.put(0, 6);
hm.put(1, 2);
hm.put(2, 5);
hm.put(3, 5);
hm.put(4, 4);
hm.put(5, 5);
hm.put(6, 6);
hm.put(7, 3);
hm.put(8, 7);
hm.put(9, 6);
long count=0;
//System.out.println(hm.get(9));
for(int i=0;i<str.length();i++)
{
count+=hm.get((int)str.charAt(i));
}
System.out.println(count);
Upvotes: 1
Views: 72
Reputation: 1688
If you want to get rid of the type casting declare a map as
HashMap<Character,Integer> hm =new HashMap<Character,Integer>();
hm.put('0', 6);
hm.put('1', 2);
hm.put('2', 5);
.....
long count=0;
for(int i=0;i<str.length();i++)
{
count+=hm.get(str.charAt(i));
}
Upvotes: 1
Reputation: 954
Maybe the following code is a better choice
firstly you should check that the expression str.charAt(i)
can be as a digit. then the digit should exists in the hashmap
char ch = str.charAt(i);
if (Character.isDigit(ch)) {
if (hm.containsKey(Integer.parseInt(String.valueOf(ch)))) {
count+=hm.get(Integer.parseInt(String.valueOf(ch)));
}
}
hope that helped
Upvotes: 0
Reputation: 111259
When you cast the char
that the charAt
method returns to int
you get the Unicode code point for the character. For example (int)'1'
will give you 49, but your map does not have an entry for 49.
To solve this you could define the mapping as HashMap<Character, Integer>
, or use Character.getNumericValue
instead of casting to int.
hm.get(Character.getNumericValue(str.charAt(i)));
Upvotes: 0