添加在用户选择 C# 控制台中不存在的索引时显示的消息

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

您好,我是编程方面的新手,目前正在学习 C#,所以请多多包涵。我目前一直在尝试为 user.Tried 不同的方法显示“索引不存在”,但我一直收到错误。我环顾四周,但找不到与我正在做的事情类似的东西。这是我当前的代码:

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

谢谢。

您应该更改您编写的代码的顺序。现在,您正试图访问一个数组(数组索引可能不正确)。

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

尝试以下正确断言超出范围的方法。

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