当使用while循环将项目添加到列表框时,程序将失败

本文关键字:列表 失败 程序 添加 while 循环 项目 | 更新日期: 2023-09-27 18:26:44

我正在尝试制作一个简单的距离计算器,输出全程行驶的英里数以用户定义的速度将用户定义的时间的值添加到列表框。我使用了一系列IF语句来捕获任何无效的输入。加载后,我可以输入无效的输入,它正常工作,所以我知道问题与我的if有关。当我输入正确的数字时,整个程序冻结,然后windows告诉我它已经退出响应。我以前从未遇到过这样的问题。

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");
    }
}

当使用while循环将项目添加到列表框时,程序将失败

您需要用大括号包装循环内容。目前,++loopCounter命令不在while循环的范围内,并且从未在任何迭代中运行,这导致它无限循环,并导致程序崩溃。如果没有大括号,while循环只在下一行运行命令。支架迫使它在范围内。

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

是一个无限循环,因为如果没有{},while循环只包含while之后的下一个语句。因此,loopCounter从不递增,并且该条件始终为真。您需要使用:

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