【问题标题】:User input row and column size for a 2-D array with Random numbers filling it C#使用随机数填充的二维数组的用户输入行和列大小 C#
【发布时间】:2021-07-05 11:24:33
【问题描述】:

您好,我对编码非常陌生,正在尝试弄清楚如何创建二维数组。这要求用户输入行和列大小,而不是用随机数填充那些选择的行和列大小。经过几天的努力,我决定来这里寻求帮助。到目前为止,这是我所拥有的,它遍布我所知道的所有地方。

                char row = 'i';
                char column = 'j';
                int[,] twoDarray = new int[row, column];
                
                int min = 0;
                int max = 100;
                Random randNum = new Random();
                for (int i = 0; i < twoDarray.Length; ++i)
                
                for (int j = 0; j < twoDarray.Length; ++j) 
                
                {
                   twoDarray[i, j] = Convert.ToInt32(In.ReadLine());
                }
                    

【问题讨论】:

标签: c# for-loop multidimensional-array random user-input


【解决方案1】:

不确定我是否理解您的问题。我假设它是一个控制台应用程序。在这种情况下,代码可能如下所示:

          int row, column;
            
           string rowVal;
            Console.Write("\nEnter Number of Rows: ");
            rowVal = Console.ReadLine();            

            string colVal;
            Console.Write("\nEnter Number of Columns: ");
            colVal = Console.ReadLine();            

            bool allGood = true;
            if(!int.TryParse(rowVal, out row))
            {
                allGood = false;
                Console.Write("Number of Rows is wrong: ");
            }


            if (!int.TryParse(colVal, out column))
            {
                allGood = false;
                Console.Write("Number of Columns is wrong: ");
            }

            if (!allGood)
                throw new Exception("Wrong input data"); //or just return from your method

            int[,] twoDarray = new int[row, column];

            int min = 0;
            int max = 100;
            Random randNum = new Random();
            for (int i = 0; i < twoDarray.GetLength(0); ++i)
            {
                for (int j = 0; j < twoDarray.GetLength(1); ++j)
                {
                    twoDarray[i, j] = randNum.Next(min,max);
                }
            }

【讨论】:

    猜你喜欢
    • 2012-07-27
    • 2018-10-12
    • 2012-08-21
    • 2015-06-25
    • 1970-01-01
    • 2014-05-10
    • 1970-01-01
    • 1970-01-01
    • 2019-02-26
    相关资源
    最近更新 更多