简体   繁体   English

带有用户定义的行数和列数的C#Jagged数组

[英]C# Jagged Array With User-Defined Number of Rows and Columns

I am trying to create a program that will create an array where the user will enter in the number of rows and columns and then the code will populate the array with random numbers between 0 and 100. Visual Studio shows no errors in the code, but the app crashes when I enter in the value for the columns and the app displays: "Unhandled Exception: System.RankException: Only single dimension arrays are supported here." 我正在尝试创建一个程序,它将创建一个数组,用户将在其中输入行数和列数,然后代码将使用0到100之间的随机数填充数组.Visual Studio在代码中没有显示错误,但是当我输入列的值并且应用程序显示时,应用程序崩溃:“未处理的异常:System.RankException:此处仅支持单维数组。”

I'm not sure where I'm going wrong, but if anyone could point me in the correct direction, I would appreciate it. 我不确定我哪里出错了,但是如果有人能指出我正确的方向,我会很感激。 Thank you. 谢谢。

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));
    }
}
}
int[,] randomArray = new int[row, column];

that's not a jagged Array, that's a 2-dimensional array. 这不是一个锯齿状的数组,而是一个二维数组。 Jagged Arrays can be defined through 锯齿状阵列可以通过定义

 int[][] 

... take a look at msdn's article about jagged arrays ...看看msdn关于锯齿状数组文章

Maybe I can recommend 也许我可以推荐

List<List<int>> 

or 要么

List<int[]> 

for your usage. 供您使用。

The first thing I notice about your main() function is that you initialize the array before you actually get the row and column values. 我注意到main()函数的第一件事是在实际获取行和列值之前初始化数组。 Surely you would need to get the user's input on array size and then initialize the array? 当然你需要获取用户对数组大小的输入,然后初始化数组?

If I understand what you are trying to do correctly, then it may make more sense to have your GetLargestNumber method as such: 如果我理解您正在尝试正确执行的操作,那么将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;
    }

This means you no longer need the call to Array.IndexOf which is (as mentioned in other answers) the source of the error you are getting. 这意味着您不再需要调用Array.IndexOf,这是(如其他答案中所述)您获得的错误的来源。

By fixing the mentioned problems, I get this: 通过解决上述问题,我得到了这个:

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

Which works well for me! 哪个适合我!

As the other answers have pointed out, there are a lot of optimizations you can make to your code - the use of jagged arrays is one of them. 正如其他答案所指出的那样,您可以对代码进行大量优化 - 使用锯齿状数组就是其中之一。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM