2014-04-07 27 views
1

我试图创建字加密和解密使用Java。已经初始化字母的字符数组,我试图通过复制到字符类的另一个数组为了做Collections.shuffle洗牌它(并创建隐窝代码)。我没有收到任何编译错误,但尝试运行代码时发生NullPointerException。不要让我知道如果您有任何洞察我的问题:洗牌字符数组在Java中产生NullPointerException异常

我的密文构造洗牌字母:

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) 

回答

4

的问题是在这里。

Character[] anAlphabet = new Character[alphabet.length]; 
for (int i = 0; i < alphabet.length; i++) { 
    alphabet[i] = anAlphabet[i]; 
} 

它创建了一个Character数组,但所有的值都在它(对于Object默认值)初始化为null

当你做alphabet[i] = anAlphabet[i];,它unboxes的Character对象来获取它的字符值。

所以基本上是相同的,因为这

alphabet[i] = anAlphabet[i].charValue(); 

由于阵列中的所有值都null,你得到了NPE。

看你的代码,我想你应该只是交换你的任务:

anAlphabet[i] = alphabet[i]; 

此外,如果你想获得一个特定的字符串表示不要忘了覆盖toString方法在您的类。