I was trying to solve This problem :
And my solution was this:
import java.io.*;
import java.util.*;
public class Solution {
public static void main(String[] args) {
Scanner sc= new Scanner(System.in);
int n=sc.nextInt();
int size[]=new int[n];
String str[]= new String[n];
for(int i=0;i<n;i++)
{
// System.out.println("INSIDE LOOP");
size[i]=sc.nextInt();
// System.out.println(size[i]);
str[i]=sc.next();
}
for(int i=0;i<n;i++)
{
Map<Character,Integer> map = new HashMap<Character,Integer>();
int count=0;
int k=0;
for(int j = 0;j<size[i];j++)
{
if(map.containsKey(str[i].charAt(j)))
{
map.put(str[i].charAt(j),map.get(str[i].charAt(j)+1));
}
else
{
map.put(str[i].charAt(j),1);
}
}
for (Map.Entry<Character,Integer> var : map.entrySet())
{
if(var.getValue()==1) //**NULLPOINTER EXCEPTION IS OCCURING HERE**
{
k=1;
continue;
}
if(var.getValue()%2==0)
{
count=count+var.getValue();
}
}
/*
* for (Map.Entry<Character, Integer> var : map.entrySet()) {
* if(var.getValue()==1) { count++; continue; } if(var.getValue()%2==0) {
* count++; } }
*/
System.out.println(count);
}
/* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
}
}
And no matter which method I employ to traverse its giving me the same nullpointer exception.
THIS IS THE ERROR: java.lang.NullPointerException at Solution.main(Solution.java:41)
Now, I dont understand why it would give nullpointer exception when I'm just traversing. Is the map empty? How would it be if I added key, value pairs before? How to solve this nullpointer problem?