Dlorwisdom
Dlorwisdom

Reputation: 117

On adding items to listbox with while loop, program fails

I am trying to make a simple distance calculator that outputs the miles traveled over the course of a user defined time at a user defined speed to a list box. I have used a series of IF statements to catch any invalid input. After its loaded I can type invalid input and it functions properly, so I know that the problem has something to do with my if. When I type in proper numbers, the whole program freezes then windows tells me that it has quit responding. I've never had a problem like this before.

int vehicleSpeed;
int hoursTraveled;
int loopCounter = 1;

private void calculateDIstanceButton_Click(object sender, EventArgs e)
{
    if (int.TryParse(vehicleSpeedTextbox.Text, out vehicleSpeed))
    {
        if (int.TryParse(hoursTravledTextbox.Text, out hoursTraveled))
        {
            while (loopCounter <= hoursTraveled)
                distanceCalculationsListBox.Items.Add("The Distance traveled after " + loopCounter + " hour is " + (vehicleSpeed * hoursTraveled));
            ++loopCounter;
        }

        else
        {
            MessageBox.Show("That is not a valid input for time");
        }
    }

    else
    {
        MessageBox.Show("That is not a valid speed input");
    }

}

Upvotes: 1

Views: 1018

Answers (2)

BradleyDotNET
BradleyDotNET

Reputation: 61369

while (loopCounter <= hoursTraveled)
                distanceCalculationsListBox.Items.Add("The Distance traveled after " + loopCounter + " hour is " + (vehicleSpeed * hoursTraveled));
++loopCounter;

Is an infinite loop, because without {} the while loop consists of only the next statement after the while. Thus, loopCounter is never incremented, and the condition is always true. You need to use:

while (loopCounter <= hoursTraveled)
{
    distanceCalculationsListBox.Items.Add("The Distance traveled after " + loopCounter + " hour is " + (vehicleSpeed * hoursTraveled));
    ++loopCounter;
}

Upvotes: 2

Dave Zych
Dave Zych

Reputation: 21887

You need to wrap your loop contents in braces. As it stands now, the ++loopCounter command is out of scope of the while loop and never gets run on any iteration, which is causing it to infinite loop and causes your program to crash. Without braces, the while loop only runs the command on the next line. The braces force it to be in scope.

while (loopCounter <= hoursTraveled)
{
    distanceCalculationsListBox.Items.Add("The Distance traveled after " + loopCounter + " hour is " + (vehicleSpeed * hoursTraveled));
    ++loopCounter;
}

Upvotes: 2

Related Questions