[Task 6] - Rounding - Please Help

Back to Problem Solutions forum

daxattwood.uk     2020-06-17 14:02:19

I'm new to coding (as a hobby) and am enjoying solving problems on Codeabbey to learn more about C#

I've been working on problem #6 for a while now and I am really having some trouble.

I'm trying to take the groups of numbers separated by spaces and new lines and populate a multidimensional array so I can perform the rounding on the numbers. I haven't got to the math part yet and am still trying to get the data into the array.

When running my code I am getting the following errors:

System.IndexOutOfRangeException: 'Index was outside the bounds of the array.'

When playing around with the numbers I sometimes get this error:

System.InvalidCastException: 'Unable to cast object of type 'System.String[]' to type 'System.IConvertible'.'

Here's my code:

class Program
{
    static void Main(string[] args)
    {
        // declare variables
        // n asks user for number of array columns
        // raw takes the numbers seperated by new lines
        int n = int.Parse(Console.ReadLine());
        string[] raw = Console.ReadLine().Split(' ');
        int[,] numbers = new int [n,2];

        // loop through raw array and split the numbers and add them to multidimentional array
        for (int i = 0; i < n; i++)
        {
            for (int j = 0; j < 2; j++)
            {
                numbers [i, j] = Convert.ToInt32(raw[n].Split(' '));
            }

        }

        // display data from multidimentional array (for testing)
        for (int i = 0; i < n; i++)
        {
            for (int j = 0; j < 2; j++)
            {
                Console.WriteLine(numbers[i,j]);
            }
        }
    }
}

I would really appreciate any assistance you can give me for where I'm going wrong. I've tried asking on stackoverflow but they were not as helpful as I expected.

Thanks in advance!

Goodwin Lu     2020-06-17 15:55:47

well, I don't know about your error in specific, but some of the numbers divided become doubles, you can't convert to int array.

Quandray     2020-06-17 19:27:34
User avatar

If you run your code with the Example Input of 4 lines, your raw variable will contain 2 numbers, but I think you are expecting it to contain more. I suggest you try printing your variables, at each stage, so you can see what they contain.

deigumnov     2020-06-18 09:51:59
User avatar

It looks like some error in this line: for (int i = 0; i < n; i++) for (int j = 0; j < 2; j++) numbers [i, j] = Convert.ToInt32(raw[n].Split(' '));

Im not so good in C#, but logically believe, that you should try to change index inside this: raw[n]. Also I think that this expression returns more than one value Convert.ToInt32(raw[n].Split(' ')).

Please login and solve 5 problems to be able to post at forum