假设我有一个球员数组列表,我想获取所有 30 岁以上的球员。球员有常用的属性,如姓名和年龄以及 getName 和 getAge 方法。我是 Java 新手,因此非常感谢这里的任何帮助。谢谢。
for(玩家 p: 玩家){ if(p.getAge() > 30){ System.out.println(p.getName()); }}
最佳答案
这是适合您的可能的解决方案。 假设:您有一个 Player 类,并且可以读取所有玩家并将其添加到 allPlayers 数组列表中。
import java.util.*;
public class game
{
//holds a list of all players.
ArrayList<Player> allPlayers = new ArrayList<Player>();
//holds a list of players older than 30 years.
ArrayList<Player> olderThan30 = new ArrayList<Player>();
public game()
{
//read players list and fill in the above arraylist with all players you have.
//for example, allPlayers = getAllPlayers(); You can also use IO methods to read external files.
//get all players that is older than 30 years of age by calling a method get30OlderPlayers().
olderThan30 = get30OlderPlayers();
}
private ArrayList<Player> get30OlderPlayers()
{
//an arraylist that will save the player list to return.
ArrayList<Player> olderThan30 = new ArrayList<Player>();
//loops through all players one by one.
for (Player p : allPlayers)
{
//if the player's age is more than 30....
if(p.getAge() > 30)
{
//...add it to the arraylist olderThan30.
olderThan30.add(p);
}
}
//at the end return the arraylist that holds the players older than 30.
return olderThan30;
}
}
祝你好运。
关于java - 玩家对象数量超过 30 个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30825239/