I’m getting a NullPointerException and can’t figure out why. I have read a lot of the questions on here and can’t seem to dissect anything well enough to get the answers I need. I’m working with a HashMap and I’m trying to reference it from a different module.
Here is the code:
import java.util.*;
@SuppressWarnings("unused")
public class Decoder
{
public static void main(String[] args)
{
decrypt();
keywork(null);
}
static void decrypt()
{
String codedline = "ilyh wkrxvdqg, wzr kxqguhg dqg qlqhwb-wkuhh".toLowerCase();
char[] cwarr = codedline.toCharArray();
String dcline = "";
for(char x : cwarr)
{
if(Character.isLetter(x))
{
int c = (int)x;
c = c - 3;
if(c > 90 && c < 97)
{
c += 26;
}
x = (char)c;
dcline += x;
} else
{
dcline += x;
}
}
System.out.println(dcline);
}
static void keywork(String dcline)
{
int x;
for(int i = 1, sw = 0; i == dcline.length(); i++)
{
String strchk = dcline.substring(sw, i);
Object n = hm.get(strchk);
};
}
static final HashMap<String, Integer> hm = new HashMap <String, Integer>()
{
/**
*
*/
private static final long serialVersionUID = 2688387173090905196L;
{
hm.put("ONE", 1);
hm.put("TWO", 2);
hm.put("THREE", 3);
hm.put("FOUR", 4);
hm.put("FIVE", 5);
hm.put("SIX", 6);
hm.put("SEVEN", 7);
hm.put("EIGHT", 8);
hm.put("NINE", 9);
hm.put("TEN", 10);
hm.put("ELEVEN", 11);
hm.put("TWELVE", 12);
hm.put("THIRTEEN", 13);
hm.put("FOURTEEN", 14);
hm.put("FIFTEEN", 15);
hm.put("SIXTEEN", 16);
hm.put("SEVENTEEN", 17);
hm.put("EIGHTEEN", 18);
hm.put("NINETEEN", 19);
hm.put("TWENTY", 20);
hm.put("THIRTY", 30);
hm.put("FOURTY", 40);
hm.put("FIFTY", 50);
hm.put("SIXTY", 60);
hm.put("SEVENTY", 70);
hm.put("EIGHTY", 80);
hm.put("NINETY", 90);
hm.put("HUNDRED", 100);
hm.put("THOUSAND", 1000);
}
};
}
This is what I’m getting:
java.lang.ExceptionInInitializerError
Caused by: java.lang.NullPointerException
at Decoder$1.<init>(Decoder.java:56)
at Decoder.<clinit>(Decoder.java:49)
Exception in thread "main"
I have never done what you’re trying to do so I don’t know if it will work the way I think it will, but I can see exactly what’s wrong.
You have used an anonymous subclass syntax with your declaration (probably by accident):
The result of that is that, during the initialization of
hm, you reference it, which (since you’re currently running inhm‘s constructor, is uninitialized. I’m frankly not even sure how that managed to compile but you should be able to make it work with the following.