[英]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.