2016-04-09 21 views
-1

現在のところ、これは1つの行に0だけを表示するテーブルを表示し、Console.Write(string.Format( "{0,6} |)"に対してindexOutOfRangeExceptionをスローします。arr [j、私]));私は各テキストファイルの情報を表形式で印刷したいと思います。2D配列の列に1D配列を格納するにはどうすればよいですか?

// 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(); 
} 
+0

、ダブルスのあなたの配列の宣言は(? 'arr')識別子が欠落しているようです。 –

+0

ありがとう、私は元のコードでそれを持っていた...ちょうど正しく上にコピーされませんでした。 – MrLogic

+0

可能な複製:http://stackoverflow.com/questions/20940979/what-is-indexoutofrangeexception-and-how-do-i-fix-it – Mikanikal

答えて

0

問題がどこにあるかあなたのエラーメッセージがわかります。

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

2次元配列[6,1021]を作成します。あなたが値を読み取るために行くとき、あなたは後方それらにアクセス

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は

ザ・あなたはそれへの書き込みを制御する2つの変数を作成します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); 
} 
+0

私はそれを変更しましたが、テーブルの形式では0しか表示されません – MrLogic

関連する問題