我正在学习java,现在我正在研究循环。我写了这段代码:
players[0] = new Player(1, "Paul", "Point Guard");
players[1] = new Player(24, "Bryant", "Shooting Guard");
players[2] = new Player (6, "James", "Small Foward");
players[3] = new Player (21, "Duncan", "Power Foward");
players[4] = new Player (12, "Howard", "Center");
players[5] = new Player (6, "Erving", "Small Foward");
public String name()
{
int number = readNumber(); // read in the number
String s = "";
for(Player player: players){
// check if input number match with any number of the players
if(player.numberMatches(number))
s += player.getName() + " ";
else s = error();
}
return s;
}
error()方法只返回“没有玩家有这个号码” 我的阵列播放器中有两个具有相同编号的玩家;当我调用name()时,它返回“No Player has this nameErving” 我试图删除else语句,一切正常。为什么? 请有人帮帮我吗?
答案 0 :(得分:3)
因为每次玩家的号码与给定号码不匹配时,您都会重新分配s
。
这在逻辑上是不正确的,并且每当玩家的号码不匹配时,有效地删除所有已找到的玩家。尝试这样的事情。
public String name()
{
int number = readNumber(); // read in the number
String s = "";
for(Player player : players){
// check if input number match with any number of the players
if(player.numberMatches(number))
s += player.getName() + " ";
}
return s.equals("") ? error() : s;
}