[英]Index was out of bounds of array? c# forms
我正在尝试读取以下文本文件:(跳过前8行)并从箭头读取每列
这样做是通过将每个列值放在一个由位置和长度决定的数组中
要测试数组值是否实际捕获了列值,我想在单击另一个按钮时看到value [0]。 但是,当我运行我的应用程序时,我得到了我的索引超出数组范围的错误? 如何,当我的数组大小为3时,我不会超出该范围。
string[] val = new string[3 ]; // One of the 3 arrays - this stores column values
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
string[] lines = File.ReadAllLines(ofd.FileName).Skip(8).ToArray();
textBox1.Lines = lines;
int[] pos = new int[3] { 3, 6,18}; //setlen&pos to read specific clmn vals
int[] len = new int[3] {2, 10,28}; // only doing 3 columns right now
foreach (string line in textBox1.Lines)
{
for (int j = 0; j <= 3; j++)
{
val[j] = line.Substring(pos[j], len[j]); // THIS IS WHERE PROBLEM OCCURS
}
}
}
}
private void button2_Click(object sender, EventArgs e)
{ // Now this is where I am testing to see what actual value is stored in my //value array by simply making it show up when I click the button.
MessageBox.Show(val[0]);
}
}
}
阵列0
索引,这意味着,与3个元素的数组将具有索引元素0
, 1
,和2
。
3
超出范围,因此当您尝试访问pos[3]
或len[3]
,您的程序将引发异常。
使用j < 3
而不是j<=3
for (int j = 0; j < 3; j++)
{
val[j] = line.Substring(pos[j], len[j]); // THIS IS WHERE PROBLEM OCCURS
}
问题是,您一直要在for
语句中一直达到j == 3
。 由于数组是从零开始的,因此这将是第四个元素,因此将for
语句更改for
:
for (int j = 0; j < 3; j++)
这样您就很好了。
数组pos
有三个值。
考虑您的for循环。
它执行循环的主体4次。 有3个项目。
为了解决此问题,要遵循标准约定,请在for
循环的条件检查中使用小于(而不是小于或等于)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.