tags:

views:

206

answers:

7

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");
+4  A: 

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");
            }
        }
    }
}
FacticiusVir
The only error I get is program has stopped responding
randywhite30
It only happens when I enter Andrea,Brittany, and Eric if I enter any other name I get the message box and the program keeps running without any issues
randywhite30
This will always show the message box telling you the spelling wrong, even if you've entered Andrea or Brittany. You want the MessageBox.Show to be in an else clause after the else if.
Michael Shimmins
@Michael Shimmins: Well caught! Will correct...
FacticiusVir
+4  A: 

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?

David
how do I stop the loop
randywhite30
a) You change the value of textBox1.Text, b) More importantly, why did you *start* the loop?
FacticiusVir
I have done this with if statements but now i am looking to try doing the same thing with loops
randywhite30
@randywhite30: Application.DoEvents() is useful inside of infinite loops. More to the point, why do you want to do with loops what was previously done with conditionals? If it's a condition, use a conditional. What's the purpose of the loop?
David
no purpose just trying to learn how to program
randywhite30
@randywhite30: A loop doesn't make sense for what you're trying to do. A loop is not just a drop-in replacement for conditional `if` statements--you use a loop if you want to do something multiple times. I don't see that in your code. If you want to learn how to use loops, write a function that needs to do something repetitive many times and teach yourself loops that way.
musicfreak
@randywhite30: Consider this a valuable lesson in avoiding infinite loops, then :) As @musicfreak says, a conditional and a loop are two very different things. There's a reason apprentice carpenters don't try to use a screwdriver to drive a nail "just to learn how to build things" :)
David
A: 

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();
CanSpice
I have done that. I understand completly but I am looking to do the same thing with an loop. I understand what I am doing isnt the best way or even a way anyone would use I am just learning and thought this would be a good test.
randywhite30
If you really want to do this with a loop, then use the `break` statement to break out of your do loop as Rich suggested.
CanSpice
+6  A: 

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.

Rich
when I put in a break statement in it tells me theres no loop to exit.
randywhite30
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");
randywhite30
@randywhite30: That is correct. Your code doesn't include the curly braces for the loop, and therefore you can only execute one line inside it. Additionally, you are placing the `break;` statement after the while condition and entirely outside of the loop code. You need to do it like so: `do { [code here] break; } while ( [condition here] );`
Rich
@randywhite30, you should take a **big** step back and figure out why you are using a loop. From what I can tell there is utterly no reason to do so from your code.
Kirk Woll
A: 

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");
    }
}
Douglas
Good use of `||` here, but I want to point out for @randywhite30 that in this example that the same commission logic will execute if the text is either Andrew or Brittany. Given the example so far this is fine, however as we're branching the logic based on the person's name, it stands to reason we may want to calculate different commissions based on who the person is.
Michael Shimmins
True. If he wants to go down that route, I'd suggest a Dictionary<string, float> commissions, and Dictionary.ContainsKey: http://msdn.microsoft.com/en-us/library/kw5aaea4.aspx then he would still only have one if with two branches.
Douglas
+1  A: 

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");
    }
}
Michael Shimmins
Since the code is the same, you could merge those two case sections.
Douglas
Updated to reflect the use of either :) thanks.
Michael Shimmins
+1  A: 

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 (i.e., 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.
}
Dan Tao