做循环和while循环

use*_*022 0 c# loops

当我输入单词"Andrea"时,程序崩溃了.我猜,但我认为这是因为我在循环内部,它不知道何时停止.如果我是对的,你能告诉我如何摆脱循环.当我休息时,它告诉我没有循环结束.

private void button1_Click(object sender, EventArgs e)
        {
             do Commission.Text = (Convert.ToDouble(textBox2.Text) / 10).ToString();
          while  (textBox1.Text == "Andrea");
        break;           
        do Commission.Text = (Convert.ToDouble(textBox2.Text) / 10).ToString();
          while (textBox1.Text == "Brittany"); 
        do Commission.Text = (Convert.ToDouble(textBox2.Text) / 10).ToString();
           while  (textBox1.Text == "Eric");
        break;          
            MessageBox.Show("The spelling of the name is incorrect", "Bad Spelling");
Run Code Online (Sandbox Code Playgroud)

Ric*_*ich 6

你有textBox1.Text == "Andrea"textBox1.Text == "Brittany"你的循环条件,但你似乎没有在代码中的任何地方改变该值.因此,您有一个无限循环,这将导致您的程序崩溃.

我不确定你的程序是做什么的,但你打破循环的选择是:

  • 使用break;语句退出循环.
  • 将循环条件更改为最终可能导致的循环条件false.
  • textBox.Text在循环体中的某处更改属性.

或者,您可以使用if语句检查一次条件,并在该条件为真时执行一些代码.

编辑:

我用if语句做了这个,但现在我想尝试用循环做同样的事情

没有目的只是想学习如何编程

回应上面的评论,我将告诉你如何用循环替换if语句.就这样做:

// Check the condition before executing the code.
while (textBox1.Text == "Andrea") {
    // Execute the conditional code.
    Commission.Text = (Convert.ToDouble(textBox2.Text) / 10).ToString();

    // We actually only want to execute this code once like an if statement,
    // not while the condition is true, so break out of the loop.
    break;
}
Run Code Online (Sandbox Code Playgroud)

在您的原始帖子中,您使用的是do while循环而不是while循环.您应该记住do while,无论条件是否为真,都会执行一次.它只检查条件,看它是否应该再运行一次.该while环路,而另一方面,在执行所有,这意味着你可以替换一个之前检查的条件if语句它.

你应该记住,这是一种不好的做法.如果要根据特定条件执行代码,请使用if语句.如果要重复执行代码一定次数或某些条件为真,则使用循环.