Click here to Skip to main content
15,896,269 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I'm working on a program that can add and delete , search values from an array this specific piece of code was described to be too complex by visual studio how do I fix it. Here is the piece of code. Any other suggestions to improve my code would be appreciated.I'm still new at this

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

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


What I have tried:

Tried googling and a switch method
Posted
Updated 20-Feb-19 1:21am

1 solution

Well, I don't know about "too complex" - but it won't work.
if (itemArray[itemArray.Length] != -1 ... 

Since itemArray by definition contains itemArray.Length items and arrays start at index zero, itemArray[itemArray.Length] is outside the bounds of the array and will throw an exception: itemArray.Length - 1 is the last valid element:
if (itemArray[itemArray.Length - 1] != -1 ... 


Why are you reinventing the wheel at all?
There is already a class that can add and remove elements: List<T> Class (System.Collections.Generic) | Microsoft Docs[^] And if you look at the Reference Sources: Reference Source[^] you will find the full source code.

Quote:
Sorry I'm explaining wrong. I mean my program I'm working on gets values from the user and stores them in an array. The users can add , delete or search values from the array. So can I use List<t> Class (System.Collections.Generic) on an array.All the starting values in the array are -1 , there are 10 array objects.



A List *is* an array - with a wrapper class that provides add, delete, and so forth (and which works with Linq methods to provide searchign and oh, so much more!)

It handles the complexities for you: like moving the elements with a higher index when you delete an element.

So you can have a List of integers, and just add and delete values as needed.
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");
 
Share this answer
 
v2
Comments
Member 14156673 20-Feb-19 7:34am    
Will that remove elements work for arrays as well or just elements? Thanks for your help.
OriginalGriff 20-Feb-19 7:44am    
Sorry? You'll have to explain that in more detail - we only get exactly what you type to work with.
OriginalGriff 20-Feb-19 8:01am    
Answer updated
Member 14156673 20-Feb-19 8:02am    
Thank you so much I understand better now
OriginalGriff 20-Feb-19 8:21am    
You're welcome!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900