如何修复c#代码“indexoutofrangeexception”;未处理的
本文关键字:未处理 indexoutofrangeexception 何修复 代码 | 更新日期: 2023-09-27 18:10:18
嗨,我正在写一个代码,随机化12个月内的每一天,看看它是否下雨和下雨多少。然而,当我想把它存储在一个二维数组它恰好有一个错误,我是如此坚持,我怎么能解决它?我在程序的开头声明了这些
static int[] daysInMonth = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
const int MONTHS_IN_YEAR = 12;
这是有问题的方法
static void MakeItRain(int[][] rainfall)
{
Random Rainfall = new Random(10);
Random RainOrNot = new Random(10);
for (int j = 0; j < MONTHS_IN_YEAR; j++)
{
for (int i = 0; i < (daysInMonth[j]); i++)
{
if (RainOrNot.Next(1, 5) == 1)
{
rainfall[i][j] = Rainfall.Next(1, 28);
}
}
}
}
当你首先通过MONTHS_IN_YEAR
初始化这个锯齿数组时,你必须用正确的索引填充它
int[][] rainfall = new int[MONTHS_IN_YEAR][];
你注意到了吗?第二个数组没有初始化。这意味着你不能做foreexample
rainfall[0][0] = something;
你必须先初始化第二个数组
rainfall[0] = new int[6];
rainfall[0][0] = something;
现在你的代码应该是这样的
static void MakeItRain(int[][] rainfall)
{
Random Rainfall = new Random(10);
Random RainOrNot = new Random(10);
for (int j = 0; j < MONTHS_IN_YEAR; j++)
{
rainfall[j] = new int[daysInMonth[j]]; // initialize second array
for (int i = 0; i < (daysInMonth[j]); i++)
{
if (RainOrNot.Next(1, 5) == 1)
{
rainfall[j][i] = Rainfall.Next(1, 28);
}
}
}
}
我能够成功运行您的代码,但是当传递给MakeItRain方法的'降雨量'数组太小,方法内部的迭代无法导航时,得到了IndexOutOfRangeException。
This runs successfully:
public class Program
{
static int[] daysInMonth = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
const int MONTHS_IN_YEAR = 12;
public void Main(string[] args)
{
int[,] rain = new int[31, MONTHS_IN_YEAR];
MakeItRain(rain);
}
static void MakeItRain(int[,] rainfall)
{
Random Rainfall = new Random(10);
Random RainOrNot = new Random(10);
for (int j = 0; j < MONTHS_IN_YEAR; j++)
{
for (int i = 0; i < (daysInMonth[j]); i++)
{
if (RainOrNot.Next(1, 5) == 1)
{
rainfall[i,j] = Rainfall.Next(1, 28);
}
}
}
}
}