【问题标题】:C# Jagged Array With User-Defined Number of Rows and Columns具有用户定义的行数和列数的 C# 锯齿状数组
【发布时间】:2015-05-02 17:01:26
【问题描述】:

我正在尝试创建一个程序,该程序将创建一个数组,用户将在其中输入行数和列数,然后代码将使用 0 到 100 之间的随机数填充数组。Visual Studio 在代码,但是当我输入列的值时应用程序崩溃并且应用程序显示:“未处理的异常:System.RankException:此处仅支持单维数组。”

我不确定我哪里出错了,但如果有人能指出我正确的方向,我将不胜感激。谢谢。

using System;
using System.Collections;

namespace RandomNumberApp
{
class RandomNumberApp
{
    static void Main()
    {
        //variables
        int row = 0,
            column = 0,
            largestRandom = 0,
            maxX = 0,
            maxY = 0;

        //method calls
        row = GetRow(row);
        column = GetColumn(column);

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

        FillArray(row, column, randomArray);
        largestRandom = GetLargestNumber(ref randomArray, row, column, out maxX, out maxY);


        DisplayResults(randomArray, largestRandom, maxX, maxY);

        //determine whether user wants to run the program again
        Console.WriteLine("Do you want to create another array?");
        Console.WriteLine("Press 'Y if yes; 'N' if no");
        char userResponse;
        userResponse = Convert.ToChar(Console.ReadLine());
        if (userResponse == 'Y' || userResponse == 'y')
            Main();
    }

    //method to ask the user to enter the row size for the array
    static int GetRow(int row)
    {
        //variables
        string rawRow;

        Console.Write("Please enter the number of rows for your array: ");
        rawRow = Console.ReadLine();
        row = Convert.ToInt32(rawRow);

        return row;
    }

    //method to ask the user to enter the column size for the array    
    static int GetColumn(int column)
    {
        //variables
        string rawColumn;

        Console.WriteLine("\nPlease enter the number of columns for your array: ");
        rawColumn = Console.ReadLine();
        column = Convert.ToInt32(rawColumn);

        return column;
    }

    //method to fill the array with random numbers
    static int[,] FillArray(int row, int column, int[,] randomArray)
    {
        //creates a random variable to fill the array
        Random randFill = new Random();

        //loop to fill the array with random numbers
        for (int i = 0; i < row; i++)
        {
            for (int j = 0; j < column; j++)
            {
                randomArray[i, j] = randFill.Next(0, 100);
            }
        }
        return randomArray;
    }

    //method to find the largest number
    static int GetLargestNumber(ref int[,] randomArray, int row, int column, out int maxX, out int maxY)
    {
        int max = int.MinValue;
        maxX = -1;
        maxY = -1;

        for (int x = 0; x < column; x++)
        {
            for (int y = 0; y < row; y++)
            {
                if (randomArray[x, y] > max)
                {
                    max = randomArray[x, y];
                    maxX = x;
                    maxY = y;
                }
            }
        }
        return max;
    }

    //method to display the results
    static void DisplayResults(int[,] randomArray, int largestRandom, int maxX, int maxY)
    {

        //display the array elements in a list
        for (int i = 0; i < randomArray.GetLength(0); i++)
            for (int j = 0; j < randomArray.GetLength(1); j++)
                Console.WriteLine("{0,-3}", randomArray[i, j]);

        Console.WriteLine("\nLargest Number In Array: " + largestRandom);
        Console.WriteLine(String.Format("\nIndex Of Largest Number:\nX: {0}\nY: {1}\n ", maxX, maxY));
    }
}
}

【问题讨论】:

  • 错误信息很清楚——Array.IndexOf() 只支持一维数组。也许在这里查看一些搜索锯齿状数组的解决方案:stackoverflow.com/questions/5180566/…
  • 首先,当rowcolumn 都设置为0 时,您正在实例化数组int[,] randomArray = new int[row, column];,因此它共有0 个元素。其次,指出错误发生在哪一行会很有用。无论如何,我建议尽可能使用int[][] 而不是int[,]
  • Array.IndexOf 适用于一维数组 - 您有一个二维数组,即定义为精确行数和列数的数组,不是锯齿状数组,即一个“数组数组”,其中每个数组可以有不同的长度。锯齿状数组以[][] 而非[,] 的形式声明

标签: c# arrays multidimensional-array user-input


【解决方案1】:
int[,] randomArray = new int[row, column];

那不是一个锯齿状数组,那是一个二维数组。 锯齿状数组可以通过

来定义
 int[][] 

...看看 msdn's关于锯齿状数组的文章

也许我可以推荐

List<List<int>> 

List<int[]> 

供您使用。

【讨论】:

  • 我可能对我的术语感到困惑。对于这段代码,我应该创建一个对行和列有用户定义限制的二维数组,所以我不知道该怎么称呼它。从该定义来看,这听起来像是一个锯齿状数组,但我们应该创建一个二维数组。
【解决方案2】:

我注意到您的 main() 函数的第一件事是您在实际获取行和列值之前初始化数组。您肯定需要获取用户输入的数组大小,然后初始化数组吗?

如果我理解您要正确执行的操作,那么使用 GetLargestNumber 方法可能更有意义:

/// <summary>
    /// Returns the largest number in the array.
    /// </summary>
    /// <param name="randomArray">The array to search.</param>
    /// <param name="rows">The amount of rows in the array.</param>
    /// <param name="columns">The amount of columns in the array.</param>
    /// <param name="maxX">The x-position (column) of the largest number in the array.</param>
    /// <param name="maxY">The y-position (row) of the largest number in the array.</param>
    /// <returns></returns>
    static int GetLargestNumber(ref int[,] randomArray, int rows, int columns, out int maxX, out int maxY)
    {
        int max;
        maxX = -1;
        maxY = -1;

        for (int x = 0; x < columns; x++)
        {
            for (int y = 0; y < rows; y++)
            {
                if (randomArray[x, y] > max)
                {
                    max = randomArray[x, y];
                    maxX = x;
                    maxY = y;
                }
            }
        }


        return max;
    }

这意味着您不再需要调用 Array.IndexOf (如其他答案中所述)您遇到的错误的来源。

通过解决上述问题,我得到了这个:

static void Main()
    {
        //variables
        int row = 0,
            column = 0,
            largestRandom = 0,
            maxX = 0,
            maxY = 0;

        //method calls
        row = GetRow(row);
        column = GetColumn(column);

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

        FillArray(row, column, randomArray);
        largestRandom = GetLargestNumber(ref randomArray, row, column, out maxX, out maxY);


        DisplayResults(randomArray, largestRandom, maxX, maxY);

        //determine whether user wants to run the program again
        Console.WriteLine("Do you want to create another array?");
        Console.WriteLine("Press 'Y if yes; 'N' if no");
        char userResponse;
        userResponse = Convert.ToChar(Console.ReadLine());
        if (userResponse == 'Y' || userResponse == 'y')
            Main();
    }

    //method to ask the user to enter the row size for the array
    static int GetRow(int row)
    {
        //variables
        string rawRow;

        Console.Write("Please enter the number of rows for your array: ");
        rawRow = Console.ReadLine();
        row = Convert.ToInt32(rawRow);

        return row;
    }

    //method to ask the user to enter the column size for the array    
    static int GetColumn(int column)
    {
        //variables
        string rawColumn;

        Console.WriteLine("\nPlease enter the number of columns for your array: ");
        rawColumn = Console.ReadLine();
        column = Convert.ToInt32(rawColumn);

        return column;
    }

    //method to fill the array with random numbers
    static int[,] FillArray(int row, int column, int[,] randomArray)
    {
        //creates a random variable to fill the array
        Random randFill = new Random();

        //loop to fill the array with random numbers
        for (int i = 0; i < column; i++)
        {
            for (int j = 0; j < row; j++)
            {
                randomArray[i, j] = randFill.Next(0, 100);
            }
        }
        return randomArray;
    }

    /// <summary>
    /// Returns the largest number in the array.
    /// </summary>
    /// <param name="randomArray">The array to search.</param>
    /// <param name="rows">The amount of rows in the array.</param>
    /// <param name="columns">The amount of columns in the array.</param>
    /// <param name="maxX">The x-position (column) of the largest number in the array.</param>
    /// <param name="maxY">The y-position (row) of the largest number in the array.</param>
    /// <returns></returns>
    static int GetLargestNumber(ref int[,] randomArray, int rows, int columns, out int maxX, out int maxY)
    {
        int max = int.MinValue;
        maxX = -1;
        maxY = -1;

        for (int x = 0; x < columns; x++)
        {
            for (int y = 0; y < rows; y++)
            {
                if (randomArray[x, y] > max)
                {
                    max = randomArray[x, y];
                    maxX = x;
                    maxY = y;
                }
            }
        }


        return max;
    }

    //method to display the results
    static void DisplayResults(int[,] randomArray, int largestRandom, int maxX, int maxY)
    {

        //display the array elements in a list
        for (int i = 0; i < randomArray.GetLength(0); i++)
            for (int j = 0; j < randomArray.GetLength(1); j++)
                Console.WriteLine("{0,-3}", randomArray[i, j]);

        Console.WriteLine("\nLargest Number In Array: " + largestRandom);
        Console.WriteLine(String.Format("\nIndex Of Largest Number:\nX: {0}\nY: {1}\n ", maxX, maxY));
    }

这对我很有效!

正如其他答案所指出的,您可以对代码进行很多优化 - 锯齿状数组的使用就是其中之一。

【讨论】:

  • 谢谢。我尝试了您的建议,但在输入列数后它仍然崩溃。根据调试器,它在您拥有 if (randomArray[x, y] > max) 的位置崩溃并告诉我:“RandomNumberApp.exe 中发生'System.IndexOutOfRangeException' 类型的未处理异常附加信息:索引超出范围阵列的。”至于它是一个锯齿状数组的问题,我认为这只是一个让我的定义混淆的问题。我被告知要创建一个二维数组,其中包含用户定义的行和列限制,所以我不确定我会怎么称呼它。
  • 我能看到你的新代码吗(直到它崩溃的那一行)?如果您使用了我提供的代码,它应该会运行,因为它为我运行!
  • 我对上面的代码进行了编辑,以显示我的代码当前的样子
  • 抱歉,我刚刚把列和行搞混了!我将把我的代码编辑成现在的样子:p
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-01-23
  • 2011-10-09
  • 2015-09-23
  • 2011-06-10
  • 1970-01-01
  • 2023-03-04
  • 1970-01-01
相关资源
最近更新 更多