【问题标题】:NullPointerException when encoding string to ASCII values将字符串编码为 ASCII 值时出现 NullPointerException
【发布时间】:2013-07-11 18:59:56
【问题描述】:

我正在尝试将输入字符串更改为它的 ASCII 码。该字符串的长度不确定,我需要单独对每个字符代码进行操作。

前几天晚上我有这个工作,但由于某种原因它现在不能,我不知道为什么......我在指示的行得到一个空指针异常......

这是整个方法。

    private void encodeEnableButtonActionPerformed(java.awt.event.ActionEvent evt)      
    {                                                   
       String encoded = msgToEncrpt.getText();
       int[] text = null;
       for (int i=0; i<encoded.length(); i++)
       {
          text[i] = (int)encoded.charAt(i);//Exception occurs here.
          System.out.println(text); 
       }
     }

【问题讨论】:

    标签: java encoding nullpointerexception ascii asciiencoding


    【解决方案1】:

    您正在尝试设置一个空数组的元素。改变

    int[] text = null;
    

    int[] text = new int[encoded.length()];
    

    【讨论】:

    • @MikeSaull 我们彼此相距不到 1 秒:D
    • 嘿,你们至少可以放心,你们都比我聪明。xD
    • @TyberiusSeppala 请勾选您认为最能回答问题的答案。
    【解决方案2】:

    数组textnull,所以在初始化之前无法访问它。

    int[] text = new int[encoded.length()];
    

    此外,要正确打印数组的内容,您需要调用Arrays.toString

     System.out.println(Arrays.toString(text));
    

    【讨论】:

      【解决方案3】:
      int[] text = null;
      ....
      text[i] = ....
      

      当您尝试为其元素赋值时,您的数组为空。您必须在此操作之前创建数组,即

      int[] text = new int[encoded.length()];
      

      【讨论】:

      • 有时候,当这样的事情发生时,我觉得自己真的很愚蠢。谢谢:P
      【解决方案4】:

      问题来了

      int[] text = null;
      

      您没有正确初始化数组。为了添加元素或与之交互,您需要初始化数组。

      int[] text = new int[encoded.length()]; 
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-01-18
        • 2021-03-19
        • 2020-02-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多