请求输入并在数组中打印该位置

本文关键字:打印 位置 数组 输入 请求 | 更新日期: 2023-09-27 18:37:10

希望有人能帮忙。 我正在自学 C#,本章中的一个挑战是让我将每个月中的天数存储在一个数组中,我称之为 daysInMonth。 当程序启动时,我要要求用户输入一个介于 1 和 12 之间的数字,然后吐出与该数字对应的月份天数。

我已经搜索了这个,但一无所获。 大多数示例都与将 int 或字符串与数组中的东西匹配/查找有关,这不是我想要的。 我想要一些东西,以便如果用户输入数字 5,程序将打印出数组中第 5 个中的任何内容。 我知道这很容易,但我认为我的搜索一无所获,因为我不知道要搜索的正确术语。 任何帮助将不胜感激。

更新:

多亏了 MAV,我让它工作了。 发布程序的完整代码。

        int[] daysInMonth = new int[12] { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
        string[] monthNames = new string[12] { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" };
        int myChoice;
        Console.Write("Please enter a number: ");
        myChoice = Int32.Parse(Console.ReadLine());
        if (myChoice < 1)
        {
            Console.WriteLine("Sorry, the number {0} is too low.  Please select a number between 1 and 12.", myChoice);
            Console.Write("Please enter a number: ");
            myChoice = Int32.Parse(Console.ReadLine());
        }
        else if (myChoice > 12)
        {
            Console.WriteLine("Sorry, the number {0} is too high.  Please select a number between 1 and 12.", myChoice);
            Console.Write("Please enter a number: ");
            myChoice = Int32.Parse(Console.ReadLine());
        }
        int i = daysInMonth[myChoice - 1];
        string m = monthNames[myChoice - 1];
        Console.WriteLine("Thank you.  You entered the number {0}.", myChoice);
        Console.WriteLine("That number corresponds with the month of {0}.", m);
        Console.WriteLine("There are {0} days in this month.", i);
        Console.ReadLine();

请求输入并在数组中打印该位置

既然你想学习C#,我就不给你我认为是答案的了。相反,我将尝试为您提供有关如何使用数组的知识,因为这似乎是您的问题。

您可以像这样声明数组:

 int[] intArray = {1, 2, 3};      //This array contains 1, 2 and 3
 int[] intArray2 = new int[12];   //This array have 12 spots you can fill with values
 intArray2[2] = 42;               //element 2 in intArray2 now contains the value 42

要访问数组中的元素,您可以执行以下操作:

int i = intArray2[2];             //Integer i now contains the value 42.

有关数组以及如何使用它们的更多信息,我可以推荐阅读本教程:数组教程