【发布时间】:2014-04-07 20:51:18
【问题描述】:
我正在尝试使用 Java 创建单词加密和解密器。初始化字母表的 char 数组后,我试图通过复制到另一个 Character 类数组中来对其进行洗牌(并创建加密代码)以执行 Collections.shuffle。我没有收到任何编译错误,但在尝试运行代码时会收到 NullPointerException。如果您对我的问题有任何见解,请告诉我:
我的 Cryptogram 构造函数来打乱字母表:
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];
}
}
我的用户输入类:
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
}
}
例外:
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)
【问题讨论】: