【解決方法】未処理の例外。 System.collections.generic.keynotfoundexception: 指定されたキー ‘string team’ がディクショナリに存在しませんでした。

プログラミングQA

[ad_1]

私が直面している問題は、プレイヤーの名前を入力するとエラーメッセージが表示されることです

<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

辞書&スイッチケースメニューのオリジナルコード

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

私が試したこと:

私は単純なものを使用しようとしました:

if (players.ContainsKey(playerName))
            {
                Console.WriteLine("Player already exists.");
                continue;
            }

ただし、コードを実行すると、プレーヤーの名前が次の場所に表示されません。

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

コードがどのように間違っているのか正確に把握できません。

解決策 1

ユーザーにチーム名を入力してもらい、入力した値をキーとして辞書にエントリを追加します。

次に、ユーザーが何を入力したかに関係なく、「string team」というチームにプレイヤーを追加しようとします。

ユーザーがチーム名として「string team」を入力しない限り、それは機能しません。

あなたの AddTeam ユーザーが入力したチーム名を返すか、 Team オブジェクト自体:

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.");
    }
}

戻り値が null、そしてそれをあなたのに渡します AddPlayer 方法:

C#
case "1":
    string teamName = AddTeam();
    if (teamName != null) AddPlayer(teamName);

編集: チームの名簿については、 ToString 上のメソッド Team クラスを更新するか、 ListTeamRoster 必要な詳細を表示するメソッド:

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

[ad_2]

コメント

タイトルとURLをコピーしました