Почему я не могу получить пользовательский ввод для элементов списка через окно консоли? - PullRequest
0 голосов
/ 13 февраля 2019

Я новичок в программировании.Теперь я должен изучить элементы списка C #.

Мои ожидания:

  1. Создать пустой список
  2. Получить значение ввода для этого спискаот пользователя через окно консоли.

Моя программа:

using System;
using System.Collections.Generic;


 namespace Indexof_in_List
 {
    class Program
   {
    static void Main(string[] args)
    {
        Console.WriteLine("Implementation of IndexOf Method with List");
        Console.WriteLine();
    //If the user entered empty value or nothing in the console window, the window will exit automatically

        //Create an Empty List
        List<int> name = new List<int>();

        Console.WriteLine("Enter the Input values for the List");

        //Get the Inputs for the List from the Console Window
        for (int n = 0; n < name.Count; n++)
        {
            bool check;
            string input = Console.ReadLine();
            check = int.TryParse(input, out int val);
            if (check)
            {
                name[n] = val;
            }
            else
            {
                Environment.Exit(0);
            }
        }

        //Implement Index of any number in the list items which you have entered to the console
        Console.WriteLine("The Index of value 10 is = {0}",name.IndexOf(10));
        Console.WriteLine();

        Console.WriteLine("The Index of value 1000 is ={0}", name.IndexOf(1000));
        Console.WriteLine();

        Console.ReadKey();
    }
}
}

Вывод: Console Output

Может кто-нибудь сказать мне решение для этой логики C #?А также скажите мне причину этого сбоя?

И скажите, правильна моя логика или нет?

Ответы [ 2 ]

0 голосов
/ 13 февраля 2019

Спасибо за ваши ценные комментарии.Наконец, я сделал последние изменения на основе ваших отзывов.

Мой код:

using System;
using System.Collections.Generic;


 namespace Indexof_in_List
 {
 class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("Implementation of IndexOf Method with List");
        Console.WriteLine();

        //Create an Empty List
        List<int> name = new List<int>();


        //If the user entered empty value or nothing in the console window, the window will exit automatically
        Console.WriteLine("Enter the Input values for the List");

        //Get the Inputs for the List from the Console Window
        for (int n=0;n<5;n++)
        {
            bool check=false;
            string input = Console.ReadLine();
            check = int.TryParse(input, out int val);
            if (check)
            {
                name.Add(val) ;
            }
            else
            {
                Environment.Exit(0);
            }
        }
        if (name.Count != 0)
        {
            //Implement Index of any number in the list items which you have entered to the console
            int index1 = name.IndexOf(10);
            Console.WriteLine("The Index of value 10 is = {0}", name.IndexOf(10));
            if (index1!=-1)
            {
                Console.WriteLine("The number 10 found in the List");
            }
            else
            {
                Console.WriteLine("The Number 10 found in the List");
            }

            int index2 = name.IndexOf(1000);
            Console.WriteLine("The Index of value 1000 is ={0}", name.IndexOf(1000));
            if (index2 != -1)
            {
                Console.WriteLine("The number 1000  found in the List");
            }
            else
            {
                Console.WriteLine("The  Number 1000 not found in the List");
            }
            Console.WriteLine();
        }


        Console.ReadKey();
    }
}
  }
0 голосов
/ 13 февраля 2019

Ваш код имеет несколько проблем:

  1. Count возвращает текущее количество элементов в вашем списке.
  2. Вы создали свой список, используяконструктор по умолчанию, поэтому Capacity также равен 0. Из-за этого вы не можете выполнить цикл от 0 до name.Capacity.
  3. Вы пытаетесь добавить элементы, используя индекс.Вы можете получить доступ только к существующим элементам , используя синтаксис name[index].

Самое простое решение - инициализировать список таким, какой вы есть, и просто добавить элементы:

List<int> name = new List<int>();
for (int i = 0; i < 10; ++i)
{
    bool check;
    string input = Console.ReadLine();
    check = int.TryParse(input, out int val);
    if (check)
    {
        name.Add(val);
    }
    else
    {
        Environment.Exit(0);
    }
}

Это будет читать 10 чисел один за другим и добавлять их в список.

...