Question

I have the following HashMap:

private HashMap<String, Team> allTeams = new HashMap<String, Team>();

I want to return as a String all teams in my league, otherwise return a message "no teams in league".

I have written this code:

public String getTeam()
{           
    String x = "";  

    for(Team tm : allTeams.values())
    {           
        if(tm.getStatus().equals("Added"))
        {                   
            x = x + tm.toString();  
        }    
        else
        {
            x = "there are no teams in your league";
        }
    }
    return temp;     
}

If I remove the "else" part of the conditional statement the code works.

However if I keep the "else" part, I continuously receive "there are no teams in your league" and I understand it is because once all teams have been returned there will be no further teams to return hence the "else" part of the statement is always printed.

How can I get this to work?

Was it helpful?

Solution

One way would be to check if x is empty outside of the loop, and set it if it is.

public String getTeam()
{           
    String x = "";  

    for(Team tm : allTeams.values())
    {           
        if(tm.getStatus().equals("Added"))
        {                   
            x = x + tm.toString();  
        }    
    }
    if (x.isEmpty())
    {
        x = "there are no teams in your league";
    }
    return x;     
}

I assumed you meant to return x, not temp, as temp isn't defined here.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top