Click here to Skip to main content
15,868,096 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
The problem I face is that when I type an input for the player's name then the error message shows
<pre><pre>nhandled exception. System.Collections.Generic.KeyNotFoundException: The given key 'string team' was not present in the dictionary.
   at System.Collections.Generic.Dictionary`2.get_Item(TKey key)
   at Program.<<Main>$>g__AddPlayer|0_5(String team, <>c__DisplayClass0_0& ) in /Users/ten/Desktop/NMAD/homework3-stybjs/Program.cs:line 153
   at Program.<Main>$(String[] args) in /Users/ten/Desktop/NMAD/homework3-stybjs/Program.cs:line 28


Original code for Dictionary & switch case menu
C#
void AddTeam()
{
    Console.Write("Do you want to add a team? (Y/N): ");
    string answer = Console.ReadLine().ToLower();
    if (answer == "y")
    {
        Console.Write("Enter a team name: ");
        string teamName = Console.ReadLine();
        if (teams.ContainsKey(teamName))
        {
            Console.WriteLine("Team already exists.");
            return;
        }
        else
        {
            teams.Add(teamName, new Team(teamName));
            // Team team = new Team(teamName);
            // teams.Add(teamName, team);
        }
    }
    else if (answer == "n")
    {
        Console.WriteLine("Add Team cancelled");
        return;
    }
    else
    {
        Console.WriteLine("Invalid selection. Please only enter Y or N.");
        AddTeam();
    }
}


C#
case "1":
            AddTeam();
            AddPlayer("string team");


C#
void string PromptPlayerName(string team)
{
    while(true)
    {
        Console.Write("Enter a player name: ");
        string playerName = Console.ReadLine();

        if(teams.ContainsKey(team))
        {
            if(teams[team].Players.ContainsKey(playerName)) 
            {
                Console.WriteLine($"The player's name {playerName} already exist on the team {team}");
                continue;
            }
        }
        return playerName;
    }
}

int PromptPlayerJersey(string team)
{
    while(true)
    {
        Console.Write("Enter a player's jersey number: ");
        string playerJersey = Console.ReadLine();
        if (int.TryParse(playerJersey, out int playerJerseyInt) && playerJerseyInt >= 0 && playerJerseyInt <= 99)
        {
            if(teams.ContainsKey(team))
            {
                if(teams[team].Players.ContainsKey(playerJersey)) 
                {
                    Console.WriteLine($"The player's jersey number {playerJersey} already exist on the team {team}");
                    continue;
                }
            }
            return playerJerseyInt;
        }
        else
        {
            Console.WriteLine("Invalid selection. Please only enter a valid number between 0-99.");
            continue;
        }
    }
}

string PromptPlayerPosition(string team)
{
    while(true)
    {
        Console.Write("Enter a player position: ");
        string playerPosition = Console.ReadLine();
        
        if(teams.ContainsKey(team))
        {
            if(teams[team].Players.ContainsKey(playerPosition)) 
            {
                Console.WriteLine($"The player's position {playerPosition} already exist on the team {team}");
                continue;
            }
        }
        return playerPosition;
    }
}


C#
void AddPlayer(string team)
{
    string playerName = PromptPlayerName(team);
    int playerJersey = PromptPlayerJersey(team);
    string position = PromptPlayerPosition(team);
    // re-prompt if user want to add another player
    Console.Write("Do you want to add another player? (Y/N): ");
    string answer = Console.ReadLine().ToLower();
    if (answer == "y")
    {
        AddPlayer(team);
    }
    else if (answer == "n")
    {
        Console.WriteLine("Add Player cancelled");
        return;
    }
    else
    {
        Console.WriteLine("Invalid selection. Please only enter Y or N.");
        AddPlayer(team);
    }
    // Player player = new Player(playerName, playerJersey, position);
    // players.Add(playerName, player);
    teams[team].Players.Add(playerName, new Player(playerName, playerJersey, position));
}


C#
void AddPlayer(string team)
{
    string playerName = PromptPlayerName(team);
    int playerJersey = PromptPlayerJersey(team);
    string position = PromptPlayerPosition(team);
    teams[team].Players.Add(playerName, new Player(playerName, playerJersey, position));

    while(true)
    {
        Console.Write("Do you want to add another player? (Y/N): ");
        string answer = Console.ReadLine().ToLower();
        if (answer == "y")
        {
            AddPlayer(team);
            teams[team].Players.Add(playerName, new Player(playerName, playerJersey, position));
        }
        if (answer == "n")
        {
            teams[team].Players.Add(playerName, new Player(playerName, playerJersey, position));
            Console.WriteLine("Add Player cancelled");
            return;
        }
        else
        {
            Console.WriteLine("Invalid selection. Please only enter Y or N.");
            continue;
        }
    }
}


What I have tried:

I have tried to use a simple one:
if (players.ContainsKey(playerName))
            {
                Console.WriteLine("Player already exists.");
                continue;
            }


However, when I ran a code and it won't display a player's name in:
C#
<pre>void ListTeamRoster()
{  
    Console.Write("Enter a team name to list roster: ");
    string teamName = Console.ReadLine();

    if (teams.ContainsKey(teamName))
    {
            foreach (KeyValuePair<string, Team> team in teams)

            {
                if (team.Key == teamName)
                {
                    Console.WriteLine($"{team.Value.ToString()}");
                }
            }
    }
    else
    {
        Console.WriteLine($"{teamName} does not exist.");
        return;
    }
}


I am unable to figure it out how exactly have my code gone wrong.
Posted
Updated 22-Nov-22 22:13pm
v4
Comments
Graeme_Grant 22-Nov-22 19:15pm    
How did you define the teams dictionary? It is suggesting that the key is not a string type. Please update your question so that we can see.
stybjs 23-Nov-22 2:08am    
what can I do to update my question so you can see it? what specific are you looking for? Let me know what I can show it to you.
Graeme_Grant 23-Nov-22 2:36am    
Again, how did you define the teams dictionary?
stybjs 23-Nov-22 2:42am    
Well, I define the teams dictionary as a bundle of coaches and players while it is also held a list of team names for coaches and players. Therefore, I am using it to insert in team.value for displaying all info. That is my understanding of using the teams dictionary.
Graeme_Grant 23-Nov-22 4:38am    
I can not see your screen. You need to update your question if you want help.

1 solution

You ask the user to enter a team name, and add an entry to the dictionary using the entered value as the key.

You then try to add a player to the team called "string team", regardless of what the user typed.

Unless the user entered "string team" as the team name, that will not work.

Change your AddTeam method so that it either returns the team name entered by the user, or returns the Team object itself:
C#
string AddTeam()
{
    Console.Write("Do you want to add a team? (Y/N): ");
    while (true)
    {
        string answer = Console.ReadLine().ToLower();
        if (answer == "y")
        {
            Console.Write("Enter a team name: ");
            string teamName = Console.ReadLine();
            if (teams.TryGetValue(teamName, out Team team))
            {
                Console.WriteLine("Team already exists.");
            }
            else
            {
                team = new Team(teamName);
                teams.Add(teamName, team);
            }
            
            return team.teamName;
        }
        
        if (answer == "n")
        {
            Console.WriteLine("Add Team cancelled");
            return null;
        }
        
        Console.WriteLine("Invalid selection. Please only enter Y or N.");
    }
}
Check that the returned value is not null, and then pass it to your AddPlayer method:
C#
case "1":
    string teamName = AddTeam();
    if (teamName != null) AddPlayer(teamName);

Edit: For the team roster, you either need to override the ToString method on the Team class, or update the ListTeamRoster method to display the desired details:
C#
void ListTeamRoster()
{  
    Console.Write("Enter a team name to list roster: ");
    string teamName = Console.ReadLine();
    if (!teams.TryGetValue(teamName, out Team team))
    {
        Console.WriteLine($"{teamName} does not exist.");
        return;
    }
    
    Console.WriteLine("Players:");
    foreach (KeyValuePair<string, Player> player in team.Players)
    {
        Console.WriteLine("{0}: {1}", player.Key, player.Value);
    }
    Console.WriteLine();
    
    Console.WriteLine("Coaches:");
    foreach (KeyValuePair<string, Coach> coach in team.Coaches)
    {
        Console.WriteLine("{0}: {1}", coach.Key, coach.Value);
    }
    Console.WriteLine();
}
 
Share this answer
 
v2
Comments
stybjs 23-Nov-22 5:16am    
Hmm, it doesn't solve my problem to display players and coaches because my actual result came out:

Enter a team name to list the roster: Yankees
=======Teams========

Yankees

=======Players========

=======Coaches========

so i want to make it display since I am using ToString from Team class. Only single problem is that they doesn't take two infos into dictionary I have:
 public Dictionary<string, Player> Players = new Dictionary<string, Player>();
    public Dictionary<string, Coach> Coaches = new Dictionary<string, Coach>();
Richard Deeming 23-Nov-22 5:21am    
I've updated my answer to show you how to fix your roster method.
stybjs 23-Nov-22 5:27am    
okay....
stybjs 23-Nov-22 5:30am    
quite good one but not exactly that my code will work that way because I have my override ToString
    public Team(string teamName)
    {
        TeamName = teamName;
    }
    
    public override string ToString()
    {
        string info = $"\n=======Teams========\n";
        info += $"\n{TeamName}\n";

        info += "\n=======Players========\n";
        foreach(KeyValuePair<string, Player> player in Players)
        {
            info += player.Value.ToString();
        }

        info += "\n=======Coaches========\n";
        foreach(KeyValuePair<string, Coach> coach in Coaches)
        {
            info += coach.Value.ToString();
        }
        return info;
    }
this code is actually got from two override ToString (from two different classes)
Richard Deeming 23-Nov-22 5:33am    
Using string concatenation in a loop is always a bad idea. But if you've already overridden the ToString method, then you need to explain what the problem is. If it's that you're not seeing any players or coaches in your team, then you need to debug your code to find out why you're not adding them.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900