【问题标题】:Return table from method [closed]从方法返回表[关闭]
【发布时间】:2016-07-20 23:15:38
【问题描述】:

我有一种方法可以让所有玩家参与游戏。问题是我想将它们分成两个团队。但是我怎样才能返回一张桌子?我已经尝试过 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;
}

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

【问题讨论】:

  • 你的代码在哪里?
  • 您可以返回一对,一个包含两个元素的数组(都是球员列表),一个地图,其中键是球队名称,值是球员列表,甚至是您自己的数据结构。贴一些代码
  • ArrayList 是要走的路……这并不难。阅读Collections 学习路径和谷歌一些java arraylist examples
  • 你从你所谓的“让所有玩家参与游戏”的方法中究竟得到了什么(数据结构)?

标签: java arrays arraylist multidimensional-array return


【解决方案1】:

我稍微修改了您的代码。据我了解,您的目标是根据他们的立场将您的球员分成两支球队(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;
}

【讨论】:

  • 非常感谢!只是一个小的语法问题:if( participant.getTeam() == Side.BLUE ) { { 行中的最后一个括号太多了;)
  • @Ananaskirsche 不客气。谢谢,编辑了答案以修复语法错误。
猜你喜欢
  • 2021-02-10
  • 2013-01-05
  • 2017-10-02
  • 2014-01-30
  • 2017-12-22
  • 2014-11-17
  • 2011-10-31
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多