0

So i have made a program (c#) that collects variables and performs calculations on them.

How can i prevent the menu options from causing errors? I.E. When attempting average calculation on an empty list it breaks the program.

Should i do a basic if statement with list.length > 1?
Also can anyone comment on how this looks in terms of practicality etc

using System;
using System.Collections.Generic;
using System.Linq;
namespace exercise2._2
{
    public class Program
    {
        static List<int> list = new List<int>(); //Publicly accessable list declaration for integer collection
        
        static void Main(string[] args)
        {
                        Console.WriteLine("Hello and Welcome. \n Press Any Key To Enter the Menu "); //Output - Welcome and Menu display
                        Console.ReadKey();
                        menu();
        }

        public static void menu()
        {
            { start:                                                            //Label for validation and re-entering menu 
                Console.Clear();                                                //Keeps the menu in place and displays options
                Console.WriteLine("Please Select an Option:");
                Console.WriteLine("Press 1 To Enter Numerical Values ");
                Console.WriteLine("Press 2 To Peform Sum Calculation");
                Console.WriteLine("Press 3 To Perform Average Calculation");
                Console.WriteLine("Press 4 To Perform Median Calculation");
                Console.WriteLine(" ~~ Press 5 To Quit ~~  ");
                Console.Write("\r\nSelect an Option: ");

                string ans = Console.ReadLine();                                //Declaration for menu selection
                int ans1;

                if (!int.TryParse(ans, out ans1) )                              //Data Validation for menu selection (non numerical)
                {
                    Console.WriteLine( "~~Incorrect Data Input~~ \n Press Any Key To Continue" );
                    Console.ReadKey();
                    goto start;
                }

                if (ans1 == 1)                                                   //Option 1 of the menu
                {
                    list.Clear();                                               //Clear List Method
                    Collection();                                               //Populate List Method
                }

                 else if (ans1 == 2)                                            //Option 2 - Sum
                 {
                   double total = list.Sum();                                   //Variable declaration for the sum of the list elements
                   Console.WriteLine("The Sum of the numbers is " + total);     //Display for variable
                   Console.WriteLine("~~Press Any Key to return to the menu~~");
                   Console.ReadKey();
                   goto start;                                                  //Return to menu
                 }

                 else if (ans1 == 3)                                            //Option 3 - Average
                 {
                    double average = list.Average();                            //Variable declaration for the average of the list elements
                    Console.WriteLine("The Average is "+average);               //Display for variable
                    Console.WriteLine("~~Press Any Key to return to the menu~~");
                    Console.ReadKey();
                    goto start;                                                 //Return to menu
                 }

                 else if (ans1 == 4)                                            //Option 4 - Median
                 {
                    double median;                                              //Variable declaration
                    list.Sort();                                                //Sorting list numerically
                    int length = list.Count();                                  //Variable declaration for list length
                    int halfLength = list.Count()/2;                            //Variable declaration for half list length
                    
                    if (length % 2 == 0)                                        //if statement halfing the length and execute code depending on a remainder 
                    {
                        double med1 = list.ElementAt(halfLength) + list.ElementAt(halfLength - 1);//variable collecting and adding 2 middle values if list legnth is odd
                        median = med1 / 2;                                                        //Dividing by 2 for median
                    }                  
                    else
                    {
                        median = list.ElementAt(halfLength);                                  //Listing middle value if list length is even
                    }
                    Console.WriteLine("The Median is " + median);                             //Output median value
                    Console.WriteLine("~~Press Any Key To Return To The Menu~~");             
                    Console.ReadKey();
                    goto start;
                 }

                else if (ans1 == 5)                                            //Menu option 5 - Quit
                {
                    Console.WriteLine("~~Press Any Key To Exit~~");
                    Console.ReadKey();
                }
                else                                                             //Output if a number is entered that is not in the menu
                { 
                    Console.WriteLine(" --!! Please Make A Selection From The Menu !!-- \n Press Any Key To Continue ");
                    Console.ReadKey();
                    goto start;
                }
            }
        }

        static void Collection()                            //Method for collecting List elements
        { 
            string input;                                   //Variable declaration
            int inputV;
            int i;

            Console.WriteLine("Please Enter Values, if you wish to stop enter 0"); 
           
            

            for (i = 1; i != 0; i++)                                //For loop that runs until 0 is entered
            {
            retry:                                                  //start point for data validation
                Console.WriteLine("Please enter value " + i);       //Output to collect element and inform how many have been entered
                input = Console.ReadLine();

                if (!int.TryParse(input, out inputV))               //Data validation for list elements
                {
                    Console.WriteLine("Incorrect Data Input");      
                    goto retry;
                }
                if (inputV == 0)                                    //Instructing for loop what to do when 0 is entered
                {
                    menu();                                         //Method call for menu
                }
                list.Add(inputV); //add entries to the list         //For loop result. List population
                
            }
        }
    }
}
  • 2
    C# is not C. There is no excuse for `goto` here... – J... Apr 06 '21 at 12:46
  • 1
    You have already answered yourself. If the code crashes when there are no element in the list then you need to check and prevent this situation – Steve Apr 06 '21 at 12:49
  • `[it] breaks the program.` is not a problem description. By what means did you conclude the program was "broken"? What was the expected result and what did you observe happened? Did you receive any compiler errors? If so, what were they? Any exceptions? If so, of what type, and what was the text of those exceptions? – J... Apr 06 '21 at 12:49
  • @Steve Yeah, im unsure of standard practice and advice always helps. – ChristAHFER Apr 06 '21 at 12:53
  • 1
    For future reference, that is not a compiler problem, it is a runtime issue. Robust programming will always check for invalid data conditions and handle exceptions as appropriate. – Crowcoder Apr 06 '21 at 12:54
  • @J... Why isnt goto used? A few people have said its bad practice but no evidence of such. When you select option 3 without a populated list the compiler breaks. I used another nested IF statement to check list.Count > 1 to fix – ChristAHFER Apr 06 '21 at 12:55
  • @Crowcoder Thank you, yeah that's the general idea, im pretty new to programming and after testing i've realized its not completely sealed off – ChristAHFER Apr 06 '21 at 12:57
  • @ChristAHFER Some reading for you : [What is wrong with using goto?](https://stackoverflow.com/q/3517726/327083) [GOTO still considered harmful?](https://stackoverflow.com/q/46586/327083). – J... Apr 06 '21 at 13:00

0 Answers0