If the execution reaches the last line and exists with NullPointerException, then "c" is null.
That means that the call Category c = classes.get(maxClass);
returns null. Check if the key in maxClass is available in classes object.
Unable to Iterate through a hashtable using enumeration in java
-
01-07-2022 - |
Domanda
This is the code where I am trying to print the key but it never gets executed rather it just goes to the the last line and throws null pointer exception.
Enumeration<String> keys = states.keys();
int max=0;
String maxClass="";
while(keys.hasMoreElements())
{
String key = keys.nextElement();
System.out.println(key);
if(states.get(key)>=max)
{
max=states.get(key);
maxClass=key;
}
System.out.println(maxClass);
}
System.out.println(maxClass);
Category c = classes.get(maxClass);
c.add(p);
this is the complete code of the classify function.
static void classify(ArrayList<Point> cities,Hashtable<String,Category> classes)
{
for(Point p: cities)
{
ArrayList<Point> nbours = new ArrayList<Point>();
nbours.addAll(getNbours( p,cities));
// System.out.println(p.city);
Hashtable<String,Integer> states = new Hashtable<String,Integer>();
for(Point pt : nbours)
{
//System.out.println(pt.city);
if(states.containsKey(pt.state))
{
int cnt = states.get(pt.state) + 1;
states.remove(pt.state);
states.put(pt.state,cnt);
//states.add(state,);
}
else
{
states.put(pt.state,1);
}
//System.out.println(states.get(pt.state));
}
Enumeration<String> keys = states.keys();
int max=0;
String maxClass="";
System.out.println(keys);
while(keys.hasMoreElements())
{
String key = keys.nextElement();
System.out.println(key);
if(states.get(key)>=max)
{
max=states.get(key);
maxClass=key;
}
System.out.println(maxClass);
}
System.out.println(maxClass);
Category c = classes.get(maxClass);
c.add(p);
System.out.println(p.city+ "Classified");
nbours.clear();
}
Soluzione
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow