0

Once again I cannot find a solution myself (I have tried using Array.IndexOf(db, accnum) with a pos > -1 return boolean, but have reverted to this loop after I couldn't make it work). So, I thought using db.Length would leave 'a' at the length of all the non-null elements in the array, however it seems to count the whole array, meaning that when the loop reaches a null element it causes an error. Is there a way to halt the loop count when it runs out of objects in the array?

void withdrawal()
{
    int accnum;
    double withdrawal;

    //get and parse input details
    accnum = int.Parse(tbNameEnt.Text);
    withdrawal = double.Parse(tbBalaEnt.Text);

    //check if account exists within existing objects
    int a = db.Length;
    for (int i = 0; i < a; i++)
    {
        if (db[i].GetAccNo() == accnum)
        {
            pos = i;

            //deduct from balance
            db[pos].SetBalance(db[pos].GetBalance() - withdrawal);

            WithMess(); //success message
            hide_form();
            MakeWith2.Visible = false;
            show_menu();
            break;
        }

        else if ((db[i].GetAccNo() != accnum) && (i == db.Length - 1))
        {
            //account doesn't exist message
            MessageBox.Show("Account does not exist");
        }
    }
}
2
  • I have edited your title. Please see, "Should questions include “tags” in their titles?", where the consensus is "no, they should not". Commented Feb 27, 2014 at 2:51
  • Why use an array at all? Why not use a collection, in which case there would be no "empty" items? You can just add and remove and the collection will grow and shrink. Commented Feb 27, 2014 at 2:54

1 Answer 1

1

If there are null items that pad the array.. break out of the loop when you reach one:

for (int i = 0; i < a; i++) {
   if (db[i] == null)
        break;
   // the rest

Alternatively, use LINQ to filter the null items out:

foreach (var item in db.Where(x => x != null)) {
    // loop here
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.