【发布时间】:2020-03-21 04:49:29
【问题描述】:
我有一个 Player 类型的 ArrayList,我正在尝试搜索特定字符串,但遇到了很多麻烦。
目前我使用 boolean 来查看播放器是否包含字符串。然后我使用 for loop 来搜索列表。
但它一直在输出文件的最后一行;我很确定我没有正确搜索。
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>();
}
如果有人可以帮助我,将不胜感激!
【问题讨论】:
-
int index = players.indexOf(playerName); boolean isFound = index >= 0;. -
在迭代时在循环内执行
boolean isFound = players.contains(playerName);。 -
你需要比较的“type Player”的属性是什么?
-
您能否提供测试用例(应该已经找到):请包含 playerName 和您观察到的匹配项!可能是字符编码的问题。
-
您能否更新您的帖子以声明 class Player 以便我们现在列出列表元素的类型。这会影响搜索和结果!