user10833638
user10833638

Reputation:

Bad operand types for binary operator '+' after trying to fill a new array

I'm trying to put all the integer converted elements into a new array, but I keep getting the error saying "Bad operand types for binary operators "+".

char[] array = input.toCharArray();
int[] myArray;

for (int i = 0, n = array.length; i < n; i++) {
  char character = array[i];
  int ascii = (int) character;
  **myArray** += ascii;
}

I was expecting myArray to get filled with the newly converted integers, but It doesn't work apparently.

Upvotes: 1

Views: 304

Answers (2)

Dhaval Goti
Dhaval Goti

Reputation: 457

No need to use n = array.length everytime.

char[] array = input.toCharArray();
        int[] myArray = new int[array.length];

        for (int i = 0; i < array.length; i++)
        {
            char character = array[i];
            int ascii = (int) character;
            myArray[i] = ascii;

        }

Upvotes: 0

Ryuzaki L
Ryuzaki L

Reputation: 40078

First initialise the myArray

int[] myArray = new int[array.length];

Then in the for loop just add int ascii to myArray

myArray[i]=ascii;

And your for loop is also wrong which is invalid, for loop consists of three part (initialisation, condition, increment) i will suggest you to go through some basics on loops concepts

for (int i = 0, i < array.length; i++)

Upvotes: 1

Related Questions