user1549697
user1549697

Reputation:

returning arrays in java?

In my program I am trying to return the prevScore[i] and the prevScoreName[i]. However, both return statements have errors stating that they're incompatible types (required int[], found int). I feel like it may be how I defined them in the main project (first 2 lines below). Any help would be appreciated.

prevScore = scoreChange (prevScore, score);
prevScoreName = nameChange (prevScoreName, newName);

public static int[] scoreChange (int prevScore[], int score)
{
    for (i=1; i<prevScore.length;i++){
            prevScore[i] = score;
    }
    return prevScore[i];
}

public static String[] nameChange (String prevScoreName[], String newName)
{
    for (i=1; i<prevScoreName.length;i++){
            prevScoreName[i] = newName;
    }
    return prevScoreName[i];
}

Upvotes: 0

Views: 106

Answers (3)

dykeag
dykeag

Reputation: 554

It seems like you maybe don't understand arrays. When you say public static int[] you are making reference to an entire array. (not all of its contents, but rather you are pointing to the space in memory where the array lives.) When you say public static int you are referring to just one integer.

In your method, you declared your return type as int[], which meant you were returning an entire array of integers. But your return statement was trying to return prevScore[i], which is a single integer, that just happens to be contained in the array. It would have been the same if you had wrote:

int var = prevScore[i];
return var;

Its easier to see that you are returning an integer in this example.

An array of integers is not the same as an integer, so your compiler didn't know what to do when you tried to send back a single integer when it was expecting to see an array of integers.

Upvotes: 0

Chris Dargis
Chris Dargis

Reputation: 6043

You are not returning the arrays:

return prevScoreName[i]; // Returns the String at index 'i'
return prevScore[i];     // Returns the integer at index 'i'

If you want to return actual arrays, you need to lose the [i]:

return prevScoreName;   // Returns the array
return prevScore;       // Returns the array

Additionally, there is no need to even return anything:

prevScore = scoreChange (prevScore, score);
prevScoreName = nameChange (prevScoreName, newName);

You are modifying the contents of these arrays with the function calls.

Upvotes: 3

Keith Randall
Keith Randall

Reputation: 23265

If you want to return just one item from each function, change the return types to int and String (not int[] and String[]). If you want to return whole arrays, then change the return statements to return prevScore; and return prevScoreName; (without the [i]).

Note that there's no need to return the whole array - the caller already has a reference to it. Just change the return types to void, delete the return statements, and get rid of the assignments in front of your calls.

Upvotes: 7

Related Questions