Mango
Mango

Reputation: 91

In C#, how can I pick between two items?

This may have been asked before, but if it has I can't find it. I'm writing a small game where sums are randomly generated for the user to answer, and correct + incorrect answers are counted. It works thus far, but I wish to implement a system where the game randomly picks between +, -, / and * symbols between the two randomly picked numbers and then, depending on which was picked, changes the way the correct answer is calculated. For a better idea, here is my current relevant code:

    public void makeNewSum()
    {
        var randomNum = new Random();
        num1 = randomNum.Next(0, 10);
        num2 = randomNum.Next(0, 10);
        answer = num1 + num2;
        label1.Text = num1.ToString() + " + " + num2.ToString() + " = ";
        txtAnswer.Text = "";
        txtAnswer.Focus();

The item 'label1' is where the sum that must be answered is displayed, though you can probably tell. What I'm trying to figure out is how I can tell it to choose between " + ", " - ", " / " and " * " where it currently always says " + ", and then change the variable 'answer' to reflect the symbol chosen. I was planning to use if statements to reflect the choice of symbol, but I'm lost for how to have it choose between them in the first place. Help is greatly appreciated!

Upvotes: 4

Views: 4958

Answers (2)

Henk Holterman
Henk Holterman

Reputation: 273274

You can use an array:

char[] operators = { '+', '-', '*', '/' };

and then pick one:

char op = operators[randomNum.Next(operators.Length)];

It is possible to use something else, like enum Operator { plus, minus, mult, ... } instead of char. In each case you will of course need a tiny interprator to get your own correct answer from the char / enum operator. Like:

switch(op)
{
   case '+' : 
      answer = a + b;
      break;

   case '-' : 
      answer = a - b;
      break;

   // etc
}

Upvotes: 3

Sriram Sakthivel
Sriram Sakthivel

Reputation: 73482

Try this

Random r = new Random();
char[] operators = new char[] { '+', '-', '*', '/' };
char op = operators[r.Next(0, operators.Length)];

Upvotes: 2

Related Questions