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

Time:05-09

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.

CodePudding user response:

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();
        }
    }
}

CodePudding user response:

You should change the sequence of the code you have written. Right now, you are attempting to access an array (possibly with an array index that is incorrect).

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("You chose number: "   myNumbers[userIndex]);
}

Console.ReadLine();
  • Related