Search code examples
javaencodingnullpointerexceptionasciiasciiencoding

NullPointerException when encoding string to ASCII values


I'm trying to change an input string into it's ASCII code. The string is of indeterminate length, and I need to operate on each characters code individually.

I had this working the other night, but for some reason it just won't now, and I can't figure out why... I get a null pointer exception at the indicated line...

Here is the entire method.

    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); 
       }
     }

Solution

  • int[] text = null;
    ....
    text[i] = ....
    

    Your array is null when you try to assign value to its element. You have to create array before this operation, i.e.

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