Domanda

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); 
       }
     }
È stato utile?

Soluzione 3

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()];

Altri suggerimenti

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

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()]; 
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top