-2

Why am I Getting A INDEXOUTOFBOUNDS EXCEPTION... Please assist and tell me where i am going wrong. I am a new programmer. Here is the code;

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;


namespace ArrayTextFile
{
    class Program
    {

        static void Main(string[] args)
        {
            string filename = "C:\\Users\\Kayloz\\Desktop\\Array.txt";
            System.IO.StreamWriter W;
            W = new System.IO.StreamWriter(filename);
            int i;
            string[] names = {"Anthony ","Paul ","Zlatan ","David ","Wayne ","Jose ","Marcus ","Daley","Inez ","Juan "};



            for (i = 0; i < names.Length; i++) ;
            W.Write(names[i]);
            W.Close();



    }
}

}

ryan
  • 5
  • 3
  • Where are you getting the error? – Hank Nov 16 '16 at 14:04
  • 5
    `for (i = 0; i < names.Length; i++) ;` - what do you think the value of `i` is after that loop? Note that you've got an empty loop body there... I suspect you didn't mean that. Also note that if you'd declared `i` in the `for` loop, e.g. `for (int i = 0; i < names.Length; i++)` you'd have received a compile-time error instead, as `i` wouldn't have been in scope in the next line. Finally, I'd encourage you to use `foreach` anyway. – Jon Skeet Nov 16 '16 at 14:04
  • `W.Write(names[i]);` is not included in your `for` loop, remove the `;` behind your loop and it should work. – Rabban Nov 16 '16 at 14:05
  • I actually wrote a reasonable explanation but took too long xD – Alfie Goodacre Nov 16 '16 at 14:07

2 Answers2

2

Remove that ; at for (i = 0; i < names.Length; i++) ;

Otherwise W.Write(names[i]); doesn't iterate. Currently you just iterate your empty statement ;


Remark: Since you don't need i outside your loop, you should declare it inside

for (int i = 0; i < names.Length; i++)

fubo
  • 44,811
  • 17
  • 103
  • 137
0
for (i = 0; i < names.Length; i++) {
    W.Write(names[i]);
}

W.Close();
lubilis
  • 3,942
  • 4
  • 31
  • 54