1

I'm relatively new to programming in C#. The code I am attempting to realize should provide an Array value to my variable SEAT.

private void btnFindSeat_Click(object sender, EventArgs e)
{
    int AntalSaeder = int.Parse(txtbxSeats.Text);
    int AntalPassagerer = int.Parse(txtbxPassengers.Text);


    int[] SEATARRAY;
    SEATARRAY = new int[AntalSaeder];

    int RandomTal = Randomizer.Next(1, AntalSaeder);
    int s = 0;
    int SEAT;

    listBox1.Items.Clear();

    for (int i = 1; i < AntalSaeder; i++)
    {
        for (int j = 1; j < AntalPassagerer; j++)
        {
            if (AntalPassagerer > AntalSaeder)
            {
                MessageBox.Show("Flyet er overbooket");
            }

            else if (AntalPassagerer <= AntalSaeder)
            {
                SEAT = i + j;
            }
            else
            {
                while (AntalPassagerer <= AntalSaeder)
                {
                    if (!SEATARRAY.Contains(RandomTal))
                    {
                        SEATARRAY[i] = RandomTal;
                        i++;

                        listBox2.Items.Add(SEATARRAY[RandomTal]);

                    }

                    SEATARRAY[s] = SEAT;
                    s++;
                    listBox1.Items.Add(SEATARRAY[RandomTal]);

                }
            }
        }
    }
}

For some reason the variable SEAT in:

SEATARRAY[s] = SEAT;
s++;
listBox1.Items.Add(SEATARRAY[RandomTal]);

Shows the error: Use of unassigned local variable. From my pov it should be assigned within the loop as SEAT = i + j;.

I could use some help, if anyone knows what's up.

dtb
  • 213,145
  • 36
  • 401
  • 431
mk100
  • 11
  • 1

1 Answers1

1

Just think about the case that there is a chance that the condition (AntalPassagerer <= AntalSaeder) is initially false. In this case SEAT is not initialized, because the compiler doesn't guess about the values of AntalPassagerer and AntalSaeder and the depending expressions. For the reason, that the compiler doesn't guess about your algorithm flow, the variable is possibly undeclared from the view of the compiler.

You should assert by your business logic that SEAT is initialized in any way. If you just want to get it run for debugging set SEAT initially at its declaration to any value, such as 0 or 1 or whatever: int SEAT = 0;

Christoph Meißner
  • 1,511
  • 2
  • 21
  • 40
  • Thanks a lot, i'll try that out. If you notice any obvious errors, please don't hesitate to point them out - as mentioned, I'm new at this and could use some knowledge input! – mk100 Sep 27 '13 at 13:12