如何在2D阵列的列中存储一维数组?到目前为止这是我的代码:

时间:2016-04-09 20:43:23

标签: c# arrays for-loop multidimensional-array

  

目前,这会显示一个表,其中一行只显示0,并为Console.Write抛出一个IndexOutOfRangeException(string.Format(“{0,6} |”,arr [j,i]));我想以表格格式打印每个文本文件中的信息。

// StringToDouble is a method that converts the contents of the text file to double
public static double[] Year = StringToDouble("Year.txt");     
public static double[] TMax = StringToDouble("WS1_TMax.txt");
public static double[] TMin = StringToDouble("WS1_TMin.txt");
public static double[] AF = StringToDouble("WS1_AF.txt");
public static double[] Rain = StringToDouble("WS1_Rain.txt");
public static double[] Sun = StringToDouble("WS1_Sun.txt");

static void Main(string[] args)
{
    double[,] arr = new double[6, 1021]; // 1021 is the upper bound of my array

    int rowLength = arr.GetLength(0);
    int colLength = arr.GetLength(1);

    for (int i = 0; i < rowLength; i++)
    {
        for (int j = 0; j < colLength; j++)
        {
            // The arrays Year[], TMax[], etc... are declared outside the Main
            arr[i, 1] = Year[j];
            arr[i, 2] = TMax[j];
            arr[i, 3] = TMin[j];
            arr[i, 4] = AF[j];
            arr[i, 5] = Rain[j];
            arr[i, 6] = Sun[j];
        }
    }

    Console.WriteLine("  Years|  TMax |  TMin |  AF   |  Rain |  Sun    |");
    for (int i = 0; i < rowLength; i++)
    {
        for (int j = 0; j < colLength; j++)
        {
            Console.Write(string.Format("{0,6} |", arr[j, i]));
        }
        Console.Write(Environment.NewLine);
    }
    Console.ReadKey();
}

1 个答案:

答案 0 :(得分:0)

您的错误消息会告诉您问题所在。

Console.Write(string.Format("{0,6} |", arr[j, i]));

您创建了一个二维数组[6,1021]。

你创建2个变量来控制对它的写作:

int rowLength = arr.GetLength(0); //This will be 6
int colLength = arr.GetLength(1); //This will be 1021

但是当你去读取值时,你可以向后访问它们:

for (int i = 0; i < rowLength; i++)
{
   for (int j = 0; j < colLength; j++)
   {
      Console.Write(string.Format("{0,6} |", arr[j, i]));
   }
   Console.Write(Environment.NewLine);
}

i max为6,j为1021.您将获得异常,因为j的最大值大于数组第一维中的条目数(6)。

交换这样的变量:

for (int i = 0; i < rowLength; i++)
{
   for (int j = 0; j < colLength; j++)
   {
      Console.Write(string.Format("{0,6} |", arr[i, j]));
   }
   Console.Write(Environment.NewLine);
}