1

我正在学习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() 它返回“没有玩家有这个 nameErving”我试图删除 else 语句并且一切正常。为什么?有人可以帮我吗?

4

1 回答 1

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;
}
于 2013-03-25T03:20:58.700 回答