Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
312 views
in Technique[技术] by (71.8m points)

list - How can I loop through multiple object in java

Hello I'm pretty new to java development and I'm having trouble with for loop Here is my code

        for (MatchTeam team : players) {
        for (MatchPlayer player : team.getTeamPlayers()) {
            for (Location location : arena.getLocations()) {
                player.getPlayer().teleport(location);
            }
        }
    }

Object MatchTeam is holding a list of player (getTeamPlayers) and getLocations contain two different location

I've tested this code with two player and they get teleported to the same location but they should get teleported to two different location

Any idea on how to resolve this ? Thanks !!

question from:https://stackoverflow.com/questions/65837922/how-can-i-loop-through-multiple-object-in-java

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You "teleport" each player to each location consecutively, because you iterate through all of them, and in the end they all end up in the last location they've been teleported - the last location in the list. If you want to teleport, say, first player to first location, second player to second location and so on, you can go with this code:

int currentLocation = 0;
for (MatchTeam team : players) {
    for (MatchPlayer player : team.getTeamPlayers()) {
        player.getPlayer().teleport(arena.getLocations().get(currentLocation++));
        if (currentLocation == arena.getLocations().size()) {
            currentLocation = 0;
        }
    }
}

It goes through all locations, then wraps around when the index reaches location list's size, which is an out-of-bounds index value.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...