Matthew Kelley Matthew Kelley - 11 days ago 6
C# Question

How can I increase one of two numbers in a comparative statement with a button click

I'm making a little UWP app in C# that simulates drawing straws. The problem that I'm having is that I want the user to get to a point where they click a button, and the variable baseNumber (initially set to 2 -- the fewest amount of drawn straws to make any sense) is compared to a randomly generated number that is passed through from another button event. I have this part down.

The part that is giving me fits is that I want the next user to then click the same button, and I want the baseNumber incremented by 1, and have that new number compared to the losingStraw. If that user is declared safe, I want the number to increment again for the next user with their button click, until ultimately the numbers equal each other, a user draws the short straw, and another code path is taken.

I'm very new to coding, so what I want might not even be possible. Here's an example of what I've tried, below. I have also tried variants on a do / do while and a for loop.

If I could somehow stop something like a for loop at each pass and make it wait for user input (the button press), that would be ideal. I couldn't figure that out either though.

Any help or ideas you can offer would be greatly appreciated!

private void drawButton_Click(object sender, RoutedEventArgs e)
{

int baseNumber = 2;
int losingStraw = Convert.ToInt32(drawButton.Tag);

if (baseNumber < losingStraw)
{
instructions.Text = "You are safe!";
baseNumber = baseNumber++; // that doesn't work at all. I was hoping that baseNumber
}
else
{
instructions.Text = "You have drawn the losing straw";
}

}

Answer

You have to write baseNumber++; instead of baseNumber = baseNumber++; since ++ aka the unary operators helps increases integer value by one. Thus baseNumber++; means baseNumber = baseNumber + 1;

Edit

In your case the variable int baseNumber = 2; has been declare and initialized in the event itself thus every-time the event is fired the baseNumber will be initialized by 2 and you would not be able to see any changes. Thus you can do something like this

int baseNumber; // you can do 2 here as well
public YourFormName() 
{
    baseNumber = 2; 
}  

private void drawButton_Click(object sender, RoutedEventArgs e)  
{
    int losingStraw = Convert.ToInt32(drawButton.Tag);   
    if (baseNumber < losingStraw)
    {
        instructions.Text = "You are safe!";
        baseNumber = baseNumber++; // that doesn't work at all. I was hoping that baseNumber
    }
    else
    {
        instructions.Text = "You have drawn the losing straw";
    }
}
Comments