1

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."

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));
    }
}
}
3
  • 1
    The error message is fairly clear - Array.IndexOf() only supports 1d arrays. Maybe see here for some solutions for searching jagged arrays: stackoverflow.com/questions/5180566/… Commented May 2, 2015 at 17:06
  • 1
    First of all, you're instantiating the array int[,] randomArray = new int[row, column]; when row and column are both set to 0, so it has a total of 0 elements. Second, it'll be useful to point out at which line the error occurs. In any case, I suggest using int[][] instead of int[,] whenever possible. Commented May 2, 2015 at 17:06
  • 1
    Array.IndexOf works on single dimensional arrays - you have a two dimensional array, i.e. one defined as an exact number of rows and column, not a jagged array, which is an "array of arrays", where each array can be of a different length. Jagged arrays are declared in the form [][] not [,] Commented May 2, 2015 at 17:07

2 Answers 2

2
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

Maybe I can recommend

List<List<int>> 

or

List<int[]> 

for your usage.

Sign up to request clarification or add additional context in comments.

1 Comment

I might be confused on my terminology. For this code, I am supposed to create a 2D array with a user-defined limit on rows and columns, so I'm not exactly sure what to call that. It sounds like a jagged array from that definition but we're supposed to be creating a 2D array.
1

The first thing I notice about your main() function is that you initialize the array before you actually get the row and column values. 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:

/// <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.

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.

4 Comments

Thank you. I tried your suggestions and it's still crashing after I enter in the number of columns. According the debugger, it is crashing at where you have if (randomArray[x, y] > max) and tells me: "An unhandled exception of type 'System.IndexOutOfRangeException' occurred in RandomNumberApp.exe Additional information: Index was outside the bounds of the array." As for the issues with it being a jagged array, I think that is just an issue getting my definitions mixed up. I was told to create a 2D array with a user-defined limit on rows and columns, so I'm not sure what I would call that.
Can I see your new code (up to the line where it crashes)? It should run if you have used the code I gave because it runs for me!
I edited to code above to show what my code currently looks like
Sorry, I just got the Columns and Rows mixed up! I'll edit my code to what it should be now :p

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.