Skip to main content
 首页 » 编程设计

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

2024年02月06日20zhwl

我正在尝试制作一个简单的距离计算器,用于输出在类(class)中行驶的英里数 以用户定义的速度将用户定义的时间添加到列表框。我使用了一系列 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"); 
    } 
 
} 

请您参考如下方法:

您需要将循环内容用大括号括起来。就目前而言,++loopCounter 命令超出了 while 循环的范围,并且永远不会在任何迭代中运行,这会导致它无限循环并导致程序崩溃。如果没有大括号,while 循环只会在下一行运行命令。大括号强制它在范围内。

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