0

Здраствуйте, столкнулся с таким исключением при данном коде: Данная исключение выплывает когда я вывожу указатель, потом удаляю его и после этого пытаюсь снова вывести указатель, не знаю как это исправить

class MyIndex
{
    public MyIndex()
    {

    }

    public MyIndex(string word, string pages)
    {
        this.word = word;
        this.pages = pages;
    }


    public string word;
    public string pages;
    private Dictionary<int, string> index = new Dictionary<int, string>();
    public Dictionary<int, string> Index
    {
        get { return index; }
    }


}

class Program
{
    static void Main(string[] args)
    {
        MyIndex ex = new MyIndex();
        Console.Write("Введите количество слов, которое вы желаете ввести: ");
        int quantity = int.Parse(Console.ReadLine());
        for (int i = 0; i < quantity; i++)
        {
            string text = "";
            Console.Write("Введите слово в указатель: ");
            ex.word = Console.ReadLine();
            Console.Write("Введите количество страниц для этого слова: ");
            int quantity1 = int.Parse(Console.ReadLine()); int[] pages = new int[quantity1];
            ex.pages = "";
            for (int j = 0; j < quantity1; j++)
            {

                Console.Write("Введите страницe " + j + ": ");
                pages[j] = int.Parse(Console.ReadLine());
                ex.pages += (pages[j] + ",");
            }
            text += ex.word + " " + ex.pages;
            ex.Index.Add(i, text);
        }
        Console.WriteLine("Заполните указатель: ");
        {
            int[] deletekey = new int[quantity];
            for (int i = 0; i < quantity; i++)
            {
                deletekey[i] = -1;
            }
            bool exit = true;
            do
            {
                Console.WriteLine("Выберете действие:\n1 - Вывод указателя\n2 - Удалить указатель\n3 - Exit");
                int num = int.Parse(Console.ReadLine());
                switch (num)
                {
                    case 1:
                        string output = "";
                        for (int i = 0; i < quantity; i++)
                        {
                            if (deletekey[i] == i) continue;
                            else
                            {
                                output = ex.Index[i];
                                Console.WriteLine(i + ": " + output);
                            }

                        }
                        break;
                    case 2:
                        Console.Write("Введите номер слова, которое вы желаете удалить: ");
                        int deletenumber = int.Parse(Console.ReadLine());
                        ex.Index.Remove(deletenumber);
                        for (int i = 0; i < quantity; i++)
                        {
                            if (deletekey[i] == -1) { deletekey[i] = deletenumber; break; }

                        }
                        for (int i = 0; i < quantity; i++)
                        {
                            Console.Write(deletekey[i] + " ");

                        }
                        break;
                    case 3:
                        exit = false;
                        break;
                }
            }
            while (exit == true);
        }
    }
}
1
  • 1
    Пробовали отладчиком пользоваться? 23 мая 2021 в 9:13

1 ответ 1

0

Везде, где вы пытаетесь обращаться к словарю с целью чтения или удаления - добавьте проверку:

if (index.Contains(key))
{
    //получаем доступ к элементу через index[key]
    //или удаляем его index.Remove(key)
}
else
{ 
    //выводим сообщение что данного элемента нет
    //или делаем что-то что должны делать если ключа нет, или ничего
}

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.