Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I'm trying to read the following textfile:(skipping first 8 lines) And reading from arrow each column enter image description here

And am doing so by putting each column value in an array which is dictated by position and length

To test if the array value actually captured a column value I want to see the value[0] when I click another button. But when I run my app, I get the error that my index was out of bounds of the array? How, when my array size is 3 and I don't go beyond that.

    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]);
    }
}

}

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
165 views
Welcome To Ask or Share your Answers For Others

1 Answer

arrays are 0 indexed, that means that an array with 3 elements will have elements at indexes 0, 1, and 2.

3 is out of bounds, so when you try to access pos[3] or len[3], your program will thrown an exception.

use j < 3 instead of j<=3

 for (int j = 0; j < 3; j++)
 {
     val[j] = line.Substring(pos[j], len[j]); // THIS IS WHERE PROBLEM OCCURS
 }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...