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:
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:
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:
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();
}