Member 14156673 Ответов: 1

Как сделать мой код менее сложным


Я работаю над программой , которая может добавлять и удалять значения поиска из массива этот конкретный фрагмент кода был описан visual studio как слишком сложный, как я могу это исправить. Вот фрагмент кода. Любые другие предложения по улучшению моего кода будут оценены с благодарностью.Я все еще новичок в этом деле

xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
если (itemArray[itemArray.Длина] != -1 && arrayIndex == itemArray.Длина)
{
Приставка.WriteLine ("-2: сбой, массив заполнен");
перерыв;
//Лимит достигнут
}
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
ОСТАЛЬНАЯ ЧАСТЬ КОДА

    class Program
    {
        static int[] itemArray = new int[10];

        delegate int modArrayDel(int inputValue); //delegate used for computation

        static int Add(int addValue)
        {
            // Name   : static int Add(int addValue)
            // Purpose: Add's a value to the array
            // Reuse  : Can be called in the main method
            // Input  : int addValue
            //          - the value to be added
            // Output : int addValue
            //          - adds the value to the array initialized in the main method
            // 

            int arrayIndex;
            for (arrayIndex = 0; arrayIndex < itemArray.Length; arrayIndex++)
            {
                if (addValue == itemArray[arrayIndex])
                {
                    Console.WriteLine("-1: Failure, duplicate found");
                    break;
                }

                if (itemArray[arrayIndex] == -1)
                {
                    itemArray[arrayIndex] = addValue;
                    Console.WriteLine("0: Success, not duplicate found");
                    break;
                }

                if (itemArray[itemArray.Length] != -1 && arrayIndex == itemArray.Length)
                {
                    Console.WriteLine("-2: Failure, array is full");
                    break;
                    //Limit has been reached
                }
            }

            return Convert.ToInt32(null);
        } //End of method

        static int Delete(int valueToDelete)

        {
            // Name   : static int Delete (int valueToDelete)
            // Purpose: Deletes a value from the array
            // Reuse  : Can be called in the main method
            // Input  : int valueToDelete
            //          - the value to be deleted
            // Output : int
            //          - the value has been successfully deleted
            // 

            bool found = false;
            for (int arrayIndex = 0; arrayIndex < itemArray.Length; arrayIndex++)
            {
                if (itemArray[arrayIndex] == valueToDelete)
                {
                    found = true;
                    itemArray[arrayIndex] = -1;
                    Console.WriteLine("0: Success, found and deleted");
                    break;
                }
            }

            if (found == false)
            {
                Console.WriteLine("-3: Failure, not found");
            }

            return Convert.ToInt32(null);
        } // end of method

        static void DisplayMenu()
        {
            // Name   : static void DisplayMenu()
            // Purpose: Simple displays a menu of possible commands such as add delete etc.
            // Reuse  : none printed only once
            // Input  : none
            // Output : String menu 
            //    
            // 

            Console.WriteLine("Array Modifier of Positive Integers");
            Console.WriteLine("===================================");
            Console.WriteLine("A - Add a positive integer to the array");
            Console.WriteLine("D - Delete an integer from the array");
            Console.WriteLine("S - Search for an integer in the array ");
            Console.WriteLine("P - Print contents of the array");
            Console.WriteLine("X - Exit");
        } //Method end

        static string GetMenuPrompt()
        {
            // Name   : static string GetMenuOption()
            // Purpose: Get an input from the user
            // Reuse  : Can be called from the main method a number of times
            // Input  : string input
            // Output : A simple message to prompt input

            Console.Write("Please enter A, D, S, P or X: ");
            return Console.ReadLine();
        } //Method end

        static int GetValue()
        {
            // Name   : GetValue()
            // Purpose: To get an int value from the user
            // Reuse  : Can be called from the main method a number of times to get more values.
            // Input  : int input
            // Output : A simple prompt message

            Console.Write("Please enter a positive integer: ");
            return Convert.ToInt32(Console.ReadLine());
        } //Method end

        static int LinearSearch(int searchItem)
        {
            // Name   : LinearSearch()
            // Purpose: To get an int value from the user and then scan through the array you see if its there.
            // Reuse  : Can be called from the main method a number of times if needed
            // Input  : int input
            // Output : A simple prompt message to input an int

            int arrayIndex;
            for (arrayIndex = 0; arrayIndex < itemArray.Length; arrayIndex++)
            {
                if (itemArray[arrayIndex] == searchItem)
                {
                    Console.WriteLine("Index in Array: " + searchItem);
                    break;
                }
            } // Searching process

            if (itemArray.Length != searchItem && arrayIndex == itemArray.Length)
            {
                Console.WriteLine(-1);
            } // Not found

            return Convert.ToInt32(null);
        } // End of method

        static void Main(string[] args)
        {
            // Name   : static void Main(string[] args)
            // Purpose: Main method calls other methods and initializes.
            // Reuse  : The main methods calls all other methods . So it can create as many objects from classes as it needs to
            // Input  : Methods
            // Output : The main driver for the application prompts the user to do several things by calling methods.

            modArrayDel Action = null;
            string userSelection = string.Empty;
            int userNumber = 0;
            itemArray = new int[10] { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 };
            DisplayMenu();
            userSelection = GetMenuPrompt();
            while (userSelection != "X")
            {
                switch (userSelection)
                {
                    case ("A"):
                        Action = new modArrayDel(Add);
                        userNumber = GetValue();
                        Console.WriteLine(Action(userNumber));
                        break;
                    case ("D"):
                        Action = new modArrayDel(Delete);
                        userNumber = GetValue();
                        Console.WriteLine(Action(userNumber));
                        break;
                    case ("S"):
                        Action = new modArrayDel(Search);
                        userNumber = GetValue();
                        Console.WriteLine(Action(userNumber));
                        Action = new modArrayDel(LinearSearch);
                        Console.WriteLine(Action(userNumber));
                        break;
                    case ("P"):
                        PrintArray();
                        break;
                    case ("X"):
                        break;
                    default:
                        Console.WriteLine("Invalid option, please try again");
                        break;
                }

                DisplayMenu();
                userSelection = GetMenuPrompt();
            }

            Console.ReadKey();
        } //end Main Method

        static void PrintArray()

        {
            // Name   : Print Array
            // Purpose: Simply prints the content of the array
            // Reuse  : Can be called multiple times from the main method
            // Input  : Void 
            // Output : Simply prints the content of the array

            Console.WriteLine("The array contains the following values: ");
            foreach (int a in itemArray)
            {
                Console.WriteLine(a);
            }
        } //end Method

        static int Search(int searchValue)
        {
            // Name   : Search ()
            // Purpose: Searches for a simple value in the array
            // Reuse  : Can be called multiple times from the main method to search for a value
            // Input  : an int Search value
            // Output : Simply prints if the search value was found or not found.

            bool foundFlag = false;
            for (int arrayIndex = 0; arrayIndex < itemArray.Length; arrayIndex++)
            {
                if (itemArray[arrayIndex] == searchValue)
                {
                    Console.WriteLine("0: Success, found");
                    foundFlag = true;
                    break;
                }
            }

            if (foundFlag == false)
            {
                Console.WriteLine("-4: Failure, not found");
            }

            return Convert.ToInt32(null);
        } // end Method
    }
}


Что я уже пробовал:

Пробовал гуглить и переключать метод

1 Ответов

Рейтинг:
10

OriginalGriff

Ну, я не знаю насчет "слишком сложно" - но это не сработает.

if (itemArray[itemArray.Length] != -1 ... 

С itemArray по определению содержит itemArray.Length элементы и массивы начинаются с нулевого индекса, itemArray[itemArray.Length] находится за пределами массива и вызовет исключение: itemArray.Length - 1 является ли последний допустимый элемент:
if (itemArray[itemArray.Length - 1] != -1 ... 


Зачем вообще изобретать велосипед?
Уже существует класс, который может добавлять и удалять элементы: Список<T> класса (System.Коллекции.Общая) | Майкрософт Документы[^] А если вы посмотрите на справочные источники: опорный источник[^] вы найдете полный исходный код.

Цитата:
Извини, что я неправильно объясняю. Я имею в виду, что моя программа, над которой я работаю, получает значения от пользователя и сохраняет их в массиве. Пользователи могут добавлять , удалять или искать значения из массива. Так что я могу использовать List<t> Class (System.Коллекции.Generic) на массиве.Все начальные значения в массиве равны -1 , имеется 10 объектов массива.



Список * - это массив-с классом-оболочкой, который обеспечивает добавление, удаление и т. д. (И который работает с методами Linq для обеспечения поиска и многое другое!)

Он обрабатывает сложности для вас: например, перемещение элементов с более высоким индексом при удалении элемента.

Таким образом, вы можете иметь список целых чисел и просто добавлять и удалять значения по мере необходимости.
List<int> myList = new List<int>();
myList.Add(3);
myList.Add(13);
myList.Add(23);
myList.Add(33);
myList.Remove(13);
if (myList.Contains(23)) Console.WriteLine("Yes");
if (myList.Contains(13)) Console.WriteLine("No");


Member 14156673

Будет ли это удаление элементов работать и для массивов или только для элементов? Спасибо за вашу помощь.

OriginalGriff

- Прости? Вам придется объяснить это более подробно - мы получаем только то, что вы печатаете для работы.

OriginalGriff

Ответ обновлен

Member 14156673

Спасибо Вам большое теперь я понимаю лучше

OriginalGriff

Всегда пожалуйста!