I'm trying to create word encrypted and decrypter using Java. Having initialized a char array of the alphabet, I'm attempting to shuffle it (and create the crypt code) by copying into another array of Character class in order to do Collections.shuffle. I don't get any compilation errors, but get a NullPointerException when attempting to run the code. Do let me know if you have any insight into my issue:
my Cryptogram constructor to shuffle the alphabet:
public class Cryptogram {
private char [] alphabet = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u','v', 'w', 'x', 'y', 'z' };
private char [] cryptCode;
public Cryptogram( ) {
cryptCode = new char[alphabet.length];
Character[] anAlphabet = new Character[alphabet.length];
for (int i = 0; i < alphabet.length; i++) {
alphabet[i] = anAlphabet[i];
}
List<Character> cryptList = Arrays.asList(anAlphabet);
Collections.shuffle(cryptList);
Object ob[] = cryptList.toArray();
for (int j = 0; j < anAlphabet.length; j++){
cryptCode[j] = anAlphabet[j];
}
}
my user input class:
import java.util.Scanner;
public class CryptogramClient {
public static void main( String [] args ) {
Cryptogram cg = new Cryptogram( );
System.out.println( cg ); // print alphabet and substitution code
}
}
Exception:
java.lang.NullPointerException
at Cryptogram.<init>(Cryptogram.java:39)
at CryptogramClient.main(CryptogramClient.java:16)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at edu.rice.cs.drjava.model.compiler.JavacCompiler.runCommand(JavacCompiler.java:272)
The problem is here.
Character[] anAlphabet = new Character[alphabet.length];
for (int i = 0; i < alphabet.length; i++) {
alphabet[i] = anAlphabet[i];
}
It creates a Character
array, but all values are initialized to null
in it (default value for an Object
).
When you do alphabet[i] = anAlphabet[i];
, it unboxes the Character
object to get it's character value.
So basically it's the same as this
alphabet[i] = anAlphabet[i].charValue();
Since all values in the array are null
, you got the NPE.
Looking at your code I think you should just swap your assignment:
anAlphabet[i] = alphabet[i];
Also don't forget to override the toString
method in your class if you want to get a specific String representation.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments