mikey
mikey

Reputation: 1460

For loop in java to find a player object in an array of players

I am learning java, and I am working on loops now. I have written this code:

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;
}

the error() method is just returning a "No player has this number" I have two players in my array players that have the same number; when I call name() it returns "No Player has this nameErving" I have tried to delete the else statement and all works fine. Why? Can anybody help me please?

Upvotes: 1

Views: 1206

Answers (1)

ktm5124
ktm5124

Reputation: 12123

Because you are re-assigning s every time a player's number does not match the given number.

This is logically incorrect, and effectively erases all the players that have been found, every time a player's number does not match. Try something like this instead.

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;
}

Upvotes: 3

Related Questions