I wanted to read a 2-D array and write it as a matrix to the console.My code is shown below
//To read the Array
int[][] arr = new int[3][];
for(int i=0;i<3;i++)
{
arr[i] = Array.ConvertAll(Console.ReadLine().Split(' '),aTemp => Convert.ToInt32(aTemp));
}
//To write the array as matrix to the console
for(int i=0;i<arr.GetLength(0);i++)
{
for(int j=0;j<arr.GetLength(1);j++)
{
Console.WriteLine("\t" + arr[i][j]);
}
}
However when I enter the input in the console and try to run, I am getting an Index out of bound exception in here
“ j
I then tried initializing the column too like this with both row and column
“ int [] [] arr =新的int [3] [3];”。
当时,另一个错误是说**“无效的排名说明符:预期的','或']'”
Then I tried initializing the array as below
"int[,] arr = new int[3,3];"
The invalid rank specifier error gone this time but error comes in the line of reading array elements,
probably this error may be due to not using arr[i][j] and reading each elements.
I just want to know what was the mistake in my initial code,that I don't get the value of GetLength(1).
和“ int [,] arr = new int [3,3];有什么区别?”和“ int [] [] arr = new int [3] [3];”
and also is there any optimized way to read a 2-d array like the statement,
rather than using 2 for loops.
I hope the question is clear. It would be so nice if somebody helps me with this problem. Thanks in Advance!!!
[int[,]
是multidimensional array
[int[][]
是jagged array,它是数组的数组
将锯齿状数组写入矩阵,您可以利用string.Join
连接指定数组的元素或元素的成员 集合,在每个元素之间使用指定的分隔符或 成员。
string.Join
输出
var arr = new [] {new []{1,2,3},new []{4,5,6},new []{7,8,9}};
for(int i=0;i<arr.GetLength(0);i++)
Console.WriteLine(string.Join(", ",arr[i] ));