int cannot be converted to int []

Melanie picture Melanie · Aug 27, 2017 · Viewed 24.7k times · Source

new to programming here and i keep getting the error message, 'incompatible types, int cannot be converted to int []', the question is to add R1& R2 together if they are of equal lengths and if not print a message that says 'the arrays must be same length', if that matters, not sure where im going wrong, any help would be greatly appreciated

 public int[] arrayAdd(int[] R1, int[] R2)
{
    int[] sumArray= new int[R1.length];

    if( R1.length!= R2.length)
    {
        System.out.println("The arrays must be same length");
}
else
{
    for(int i=0; i< R1.length; i++)
    for (int j=0; j<R2.length; j++)

    {

        sumArray= R1[i]+ R2[j]; // Error
    }
}
    return sumArray;
}

Answer

Stephen C picture Stephen C · Aug 27, 2017

not sure where im going wrong

You are attempting to assign an int to a variable whose type is int[].

That is not legal ... and it doesn't make sense.

This:

   sumArray= R1[i]+ R2[j];

should be this

   sumArray[something_or_other] = R1[i] + R2[j];

... except that you have a bunch of other errors which mean that a simple "point fix" won't be correct.

Hint: you do not need nested loops to add the elements of two arrays.

-- Steve