简体   繁体   中英

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

You're trying to set an element of a null array. Change

int[] text = null;

to

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

The array text is null , so you can't access it until you initialize it.

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

Additionally, to print the array's contents properly, you'll need to call Arrays.toString .

 System.out.println(Arrays.toString(text));
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, ie

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

The problem is here

int[] text = null;

You are not initializing the array properly. In order to add elements or interact with it at all, you need to initialize the array.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM