Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

index out of bounds c# (I'm trying to add savegame and am using WriteAllLines)

I am trying to make savegame for a quite simple game, and this is the code I am using right now to write money to a .txt file (NameBox is the textbox you use to write the name of the .txt file):

private void SaveBtn_Click(object sender, EventArgs e)
    {
        String filename = NameBox.Text;
        if (filename == "")
        {
            filename = "New Save";
        }
        filename += ".txt";
        String[] Money = new String[MainForm.Money];
        Money[MainForm.Money] = MainForm.Money.ToString();
        System.IO.File.WriteAllLines(filename, Money);
        Application.Exit();
    }

However I get an index out of bounds error on whatever line is after

Money[MainForm.Money] = MainForm.Money.ToString();

I've also tried doing this:

for (int i = 0; i < MainForm.Money; i++){
    Money[MainForm.Money] = MainForm.Money.ToString();
}

But it gives me an error on the closing body (squiggly bracket as I call it) I have done a savegame before with an array of walls and soldiers saving their sizes and locations using this code (wallList[i].ToString() refers to a method in the wall class that returns all the values):

private void SaveBtn_Click(object sender, EventArgs e)
    {
        String filename = filenametxt.Text;
        if (filename == "")
        {
            filename = "Level";
        }
        filename += ".txt";
        String[] lines = new String[MainForm.wallList.Count + 
        MainForm.soldierList.Count+1];
        for (int i = 0; i < MainForm.wallList.Count; i++)
        {
            lines[i] = MainForm.wallList[i].ToString();
        }
        lines[MainForm.wallList.Count] = "@";
        for (int i = 0; i < MainForm.soldierList.Count; i++)
        {
            lines[i + MainForm.wallList.Count +1] = 
            MainForm.soldierList[i].ToString();
        }
        System.IO.File.WriteAllLines(filename, lines);
        Application.Exit();
    }

I would very much appreciate if someone could help me! (Please explain to me what each part of the code means, for example explaining that .ToString() converts an int into a string)

like image 616
jomoetnt Avatar asked Jan 30 '23 16:01

jomoetnt


1 Answers

String[] Money = new String[MainForm.Money];

Here you create the array of size MainForm.Money. Say the value of MainForm.Money is 10. The array is size 10, meaning there are 10 slots. These are numbered 0-9.

Money[MainForm.Money] = MainForm.Money.ToString();

Here you do the equivalent of Money[10] when it only has slots up to 9. Thus you go "Out of Bounds" of the array.

like image 167
Tyler Avatar answered Feb 02 '23 09:02

Tyler