Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Add in a message that displays when the user selects an index that doesn’t exist in C# console

Hi I’m very new at programming and currently learning C# so please bare with me. I’m currently stuck trying to display an "index does not exist" for the user.Tried different methods but I kept getting errors. I’ve looked around but could not find something similar to what I’m doing. Here is my current code:

        int[] myNumbers = { 10, 5, 15, 20, 30 };
        Console.WriteLine("User please enter a number from 0 to 4\n");

        int userIndex = Convert.ToInt32(Console.ReadLine());
        Console.WriteLine("You chose number: " + myNumbers[userIndex]);

        if (userIndex > 4)
        {
            Console.WriteLine("Index does not exist " + myNumbers[userIndex);
        }
            

        Console.ReadLine();

Thank you.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Try the following which properly asserts out of range.

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] myNumbers = { 10, 5, 15, 20, 30 };
            Console.WriteLine("User please enter a number from 0 to 4\n");

            int userIndex = Convert.ToInt32(Console.ReadLine());

            if (userIndex <= 4)
            {
                Console.WriteLine("Index does not exist " + myNumbers[userIndex]);
            }
            else
            {
                Console.WriteLine($"{userIndex} is out of range ");
            }


            Console.ReadLine();
        }
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading