Kappamaster222 Kappamaster222 - 1 month ago 7
C# Question

C# substract 2 strings without getting negatives

i need some help with my code.
i've got to make a math game with subtracting without getting negatives but my code doesn't seem to work.

int c = a - b;
if (c < 0)
{
Random ro = new Random();
a = ro.Next(10) + 1;
b = ro.Next(10) + 1;
lb_getal1.Text = a.ToString();
lb_getal2.Text = b.ToString();
}
if (txt_antwoord.Text == c.ToString())
{
MessageBox.Show("You provided the right answer!");
score += 1;

Random r = new Random();
a = r.Next(10) + 1;
b = r.Next(10) + 1;
lb_getal1.Text = a.ToString();
lb_getal2.Text = b.ToString();
}
else
{
MessageBox.Show("You were wrong!");
}
if (score == 5)
{
MessageBox.Show("You answered 5 answers correctly! Well done!");
this.Close();
RM_menu form = new RM_menu();
form.Show();
}

Answer

There are several problems in your code. The first thing to improve is: use only one instance of Random.

The Random class provides pseudo random numbers from a list. If you create an instance with the default constructor new Random(), the instance is initialized with a seed taken from the current time. Since there is not much time between your two calls, both instances probably use the same seed and you will get the same values for a and b again.
I suggest to create only one instance and store it in a member variable of your class.

Second problem: if your first try results in a negative c, you only try again once, but that does not make sure that this time it will be positive. A better approach is to compare a and b and switch if b is larger.

So the your code could look like this:

public class YourGame : Form // I guess it's a Form
{
    private Random randomGenerator = new Random();
    private int a;
    private int b;
    private int score;

    public void CreateQuestion()
    {
        a = randomGenerator.Next(10) + 1;
        b = randomGenerator .Next(10) + 1;
        if (b > a)
        {
            // switch values
            int tmp = b;
            b = a;
            a = tmp;
        }

        lb_getal1.Text = a.ToString();
        lb_getal2.Text = b.ToString();            
    }

    private void OnAnswer()
    {
        int c = a - b; // will never be negative as we checked a and b above
        if (txt_antwoord.Text == c.ToString())
        {
            MessageBox.Show("You provided the right answer!");
            score += 1;
            CreateQuestion();
        }
        else
            MessageBox.Show("You were wrong!");

        if (score == 5)
        {
            MessageBox.Show("You answered 5 answers correctly! Well done!");
            this.Close();
            RM_menu form = new RM_menu();
            form.Show();
        }
    }
}