简体   繁体   中英

Do loops and while loops

When I type in the word "Andrea" the program crashes. I am guessing, but I think it's because I am inside the loop and it doesn't know when to stop. If I am correct can you tell me how to get out of the loop. when I put a break in it tells me there is no loop to end.

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

You have textBox1.Text == "Andrea" and textBox1.Text == "Brittany" as your loop conditions, but you don't seem to be changing that value anywhere in the code. Therefore, you have an infinite loop which will result in your program crashing.

I'm not certain what your program is meant to be doing, but your options to break out of a loop are:

  • Use a break; statement to exit the loop.
  • Change your loop condition to something which can eventually result in false .
  • Change the textBox.Text property somewhere in the loop body.

Alternatively, you could use an if statement to check the condition once, and execute some code if that condition is true.

Edit:

I have done this with if statements but now i am looking to try doing the same thing with loops

no purpose just trying to learn how to program

In response to the above comments, I'll tell you how to replace an if statement with a loop. Just do it like so:

// 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;
}

In your original post, you are using a do while loop rather than a while loop. You should keep in mind that the do while executes once for certain, regardless of whether its condition is true. It only checks the condition to see whether it should run additional times. The while loop, on the other hand, checks the condition before executing at all, which means you can substitute an if statement with it.

You should keep in mind that this is a bad practice. If you want to execute code depending on a certain condition, use an if statement. If you want to execute code repeatedly a certain number of times or while some condition is true, then use a loop.

I suspect that by while you actually mean if . Otherwise, do you get an error message or exception when the application crashes? Can you wrap this function in a try/catch to see what the exception is?

Edit To clarify, try this method body:

private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                if(textBox1.Text == "Andrea")
                {
                    Commission.Text = (Convert.ToDouble(textBox2.Text) / 10).ToString();
                }
                else if(textBox1.Text == "Brittany")
                {
                    Commission.Text = (Convert.ToDouble(textBox2.Text) / 10).ToString();
                }
                else 
                {    
                    MessageBox.Show("The spelling of the name is incorrect", "Bad Spelling");
                }
            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.ToString(), "Bad Spelling");
            }
        }
    }
}

At a glance, it looks like you have an infinite loop. As soon as you type in "Andrea" in textBox1 and click button1, it will perpetually update Commission.Text, not interrupting the thread to process any additional input.

The bigger question is, what the heck is this program supposed to be doing? And why is it doing it in a loop?

Adding to what FacticiusVir said earlier, you can also do this in a switch statement (and since we're calculating the same commissions for each person, they can be combined:

private void button1_Click(object sender, EventArgs e)
{
    switch(textBox1.Text)
    {
        case "Andrea":
        case "Brittany":
            Commission.Text = (Convert.ToDouble(textBox2.Text) / 10).ToString();
            break;
        default:
            MessageBox.Show("The spelling of the name is incorrect", "Bad Spelling");
    }
}

If you want to do different commissions per person you need to split it (in the below Brittany is getting a different commission value now):

private void button1_Click(object sender, EventArgs e)
{
    switch(textBox1.Text)
    {
        case "Andrea":
            Commission.Text = (Convert.ToDouble(textBox2.Text) / 10).ToString();
            break;
        case "Brittany":
            Commission.Text = (Convert.ToDouble(textBox2.Text) / 15).ToString();
            break;
        default:
            MessageBox.Show("The spelling of the name is incorrect", "Bad Spelling");
    }
}

The do { x } while (y) construct runs x once, and then proceeds to run x continuously as long as y is true.

You're not having any success because you seem to be structuring it like this:

do
{
    // This will just run over and over...
}
while (condition); // ...because this is always true.

break; // This isn't even in the loop!

In other words, the point where you're trying to add your break (based on a comment you left on another answer) is outside the loop, which is why your code is running indefinitely.

Now, it sounds like you're really just trying to use a do / while to emulate an if statement, presumably as a challenge to yourself. If that is the case, do yourself a favor and give up on that idea.

You cannot use a do / while loop to emulate an if condition, because do will always run at least once. The only way you could ensure that it runs exactly once under a specific condition (ie, what if does) would be by embedding an if statement inside the do loop, which would defeat the purpose of the exercise.

That said, you can emulate an if with a while :

while (condition)
{
    // Execute code once.
    break; // Then just quit.
}

Looking at this one piece:

do Commission.Text = (Convert.ToDouble(textBox2.Text) / 10).ToString();
  while  (textBox1.Text == "Andrea");

...what do you expect to happen if textBox1.Text == "Andrea" ?

What the program is doing is checking your comparison test, then if it's true, it does what is inside of the do / while block, then it checks the comparison test, then if it's true, it does what is inside of the do / while block, then it checks the comparison test, then if it's true, it does what is inside of the do / while block, then...

Get the point?

You use do / while loops if the condition is going to change inside the loop (or you explicitly break out of it).

What you want instead is to change it to something like

if( textBox1.Text == "Andrea" )
  Commission.Text = (Convert.ToDouble(textBox2.Text) / 10).ToString();

Just a guess, but as FacticiusVir says, you probably want to use conditionals instead of loops:

private void button1_Click(object sender, EventArgs e)
{
    if (textBox1.Text == "Andrea" || textBox1.Text == "Brittany")
    {
        Commission.Text = (Convert.ToDouble(textBox2.Text) / 10).ToString();
    }
    else
    {
        MessageBox.Show("The spelling of the name is incorrect", "Bad Spelling");
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM