从方法返回表

时间:2016-04-01 08:18:42

标签: java arrays arraylist multidimensional-array return

我有一种方法可以让所有玩家都参与到游戏中。问题是我想在两个团队中对它们进行排序。但是我该如何归还一张桌子呢?我已经尝试了2D阵列,但我不知道如何将球员放在最后位置。我也看到了使用2D ArrayLists的选项,但这看起来非常复杂。有没有一种优雅的方法来解决这个问题?

编辑(我目前的代码):

public String[][] getGameMembers()
{
    if(!isIngame())
    {
        return null;
    }

    //Return-Array 
    String[][] playerTable = new String[2][6];


    //Get all Players
    List<Participant> l = game.getParticipants();

    //Put each player in the Arraylist
    for(int i = 0; i < l.size(); i++)
    {
        Participant s = l.get(i);

        //Get teams and put in the right place in array
        if( l.get(i).getTeam() == Side.BLUE )
        {
            playerTable[0][playerTable.length] = s.getSummonerName() + " (" + s.getChampion() + ")" ;
        }
        else
        {
            playerTable[1][playerTable.length] = s.getSummonerName() + " (" + s.getChampion() + ")" ;
        }
    }

    return playerTable;
}

此代码不起作用,因为我不知道如何将Elements放在数组的最后位置。

1 个答案:

答案 0 :(得分:0)

我已稍微修改了您的代码。根据我的理解,你的目标是根据他们的身份将你的球员分成两队(Blue???(我假设为红色))。主要问题是由于playerTable.length,你总是插入内部数组的边界之外。通过跟踪计数器,您可以确保始终插入下一个空元素。

通过分离功能可以进一步改进代码,并且可以更智能地跟踪下一个免费元素,但这样很容易理解。

如果我误解了一定要解释我错过的东西。

public String[][] getGameMembers() {
    // Define our array
    String[][] playerTable = new String[2][6];

    if(!isIngame()) {
        return playerTable; // It's better practice to return an empty array rather than null. If an empty array is not allowed then throw an exception.
    }

    int TEAM_BLUE = 0; // Just an easy reminder in order to have more readable code
    int TEAM_RED = 1;

    int teamBlueCounter = 0; // Keep track of the next free element in team blue
    int teamRedCounter = 0; // idem

    //Get all Players
    List<Participant> participants = game.getParticipants();

    //Put each player in the Arraylist
    for(int i = 0; i < participants.size(); i++) {
        Participant participant = participants.get(i);

        String participantName = participant.getSummonerName() + " (" + participant.getChampion() + ")";

        //Get teams and put in the right place in array
        if( participant.getTeam() == Side.BLUE ) {
            playerTable[TEAM_BLUE][teamBlueCounter] = participantName;
            teamBlueCounter++;
        } else {
            playerTable[TEAM_RED][teamRedCounter] = participantName;
            teamRedCounter++;
        }
    }

    return playerTable;
}