我有一个ArrayList
Player 类型,我正在尝试搜索特定字符串,但遇到了很多麻烦。
目前我正在使用 boolean 值来查看播放器是否包含该字符串。然后我使用 for 循环 来搜索列表。
但它一直输出文件的最后一行;我很确定我没有正确搜索。
String playerName = sc.next();
boolean isFound = players.contains(playerName);
int index = 0;
for (int i = 0; i < players.size(); i++) {
if (isFound) {
break;
}
index = i;
}
System.out.println(players.get(index));
System.out.println(isFound);
我的Player类定义如下 (不确定这是否有帮助)
public class Player extends Person {
public String pos;
public int g;
public int ab;
public int r; // various statistics for the player
public Player(String name, String team, String pos) {
this.name = name;
this.team = team;
this.pos = pos;
}
我还有一个包含列表的联赛类
public class League extends loadData {
public static ArrayList<Player> players = new ArrayList<Player>();
public static ArrayList<Pitcher> pitchers = new ArrayList<Pitcher>();
}
如果有人能帮助我,我将不胜感激!
最佳答案
如果您只需要列表中某个元素的索引,请使用 List#indexOf() 。无需首先检查列表是否包含该元素,因为如果不包含该元素,该方法将返回 -1
。
示例:
List<String> players = new ArrayList<String>
players.addAll(Arrays.asList("Jim, "Bob, "Mary");
int indexOfBob = players.indexOf("Bob");
如果您计划迭代列表并对所有元素执行操作直到到达特定元素,则不需要使用两个索引整数。示例:
int i;
for(i = 0; i < players.size(); i++) {
// Perform an operation on the current player.
if(players.get(i).equals("Bob")) break;
}
关于java - 在 ArrayList 对象中搜索字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59039561/