【问题标题】:Shuffling character array in Java producing NullPointerException在 Java 中洗牌字符数组产生 NullPointerException
【发布时间】: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)

【问题讨论】:

    标签: java arrays


    【解决方案1】:

    问题就在这里。

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

    它创建了一个Character 数组,但其中的所有值都初始化为nullObject 的默认值)。

    当您执行alphabet[i] = anAlphabet[i]; 时,它会拆箱Character 对象以获取它的字符值。

    所以基本上和这个是一样的

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

    由于数组中的所有值都是null,因此您得到了 NPE。

    看看你的代码,我认为你应该交换你的任务:

    anAlphabet[i] = alphabet[i];
    

    如果您想获得特定的字符串表示,请不要忘记在您的类中覆盖 toString 方法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-01-14
      • 2016-06-19
      • 1970-01-01
      • 2012-05-09
      • 1970-01-01
      • 2015-04-15
      • 2011-07-09
      相关资源
      最近更新 更多