Search code examples
javaintbluejselection-sort

Java Error: "incompatible types: int cannot be converted to Player


I'm having trouble with my code and can't figure out how to remedy the error I'm receiving. I'm getting an error "incompatible types: int cannot be converted to Player" in the line containing team[index] = temp; Any guidance would be greatly appreciated. I'm really new to Java, and this is my first time attempting to use selection sort. I have tried looking around and searching but still haven't figured out this error after 3 days banging my head on the desk with it. Thanks in advance!

public static void selectionSort(Player[] team, int team_size)
{
    int index;
    int smallestIndex;
    int minIndex;
    int temp;

    for (index = 0; index < team_size - 1; index++)
    {
        smallestIndex = index;

        for (minIndex = index + 1; minIndex < team_size; minIndex++)
            if(team[minIndex].getNumber() < team[smallestIndex].getNumber())
                smallestIndex = minIndex;
        temp = team[smallestIndex].getNumber();
        team[smallestIndex] = team[index];
        team[index] = temp;
    }
}

Solution

  • The problem here is just what the error means. The parameter team is an array of Player objects. temp is just an int. So when you try to set team[index], which is a Player object, it cant do that.

    Are you just trying to swap the two Players in the sort? Maybe temp should be a Player

    Player temp;
    

    Then for the swap

    temp = team[smallestIndex]; //returns the actual Player instance rather than getNumber();
    team[smallestIndex] = team[index];
    team[index] = temp;
    

    Also, you probably don't want to pass in team_size as you can get the length of your Player array by using team.length. This way you don't have to rely on passing the correct length in every time. Your for loop would look like this

    for (index = 0; index < team.length; index++)