I am trying to display two random generated numbers in a text-box using visual studio.
This is what I have so far...
int RandomNumber(int min = 0, int max = 100)
{
Random random = new Random();
return random.Next(min, max);
}
int RandomNumber2(int min = 0, int max = 100)
{
Random random = new Random();
return random.Next(min, max);
}
txtQuestion.Enabled = true;
string num1 = Convert.ToString(RandomNumber());
string num2 = Convert.ToString(RandomNumber2());
txtQuestion.Text = ("{0} + {1} = ?", num1, num2);
However, the last line comes up with the error " cannot implicitly convert type '(string, string num1, string num2)' to 'string' "
How am I supposed to output these randomly generated numbers in the textbox?
Hi below is the edited code that works to how I needed it. Thanks for all the help:)
Random random1 = new Random();
I called the above function globally so I can refer to it every time I need a new random number. And below is how I used it in my function to call for two different random numbers and display them in a text-box.
int randomNumber1 = random1.Next(0, 10);
int randomNumber2 = random1.Next(0, 10);
string num1 = Convert.ToString(randomNumber1);
string num2 = Convert.ToString(randomNumber2);
txtQuestion.Text = string.Format ("{0} + {1} = ?", num1, num2);
As @John said, you are using a ValueTuple. You can learn more about ValueTuple here or on the msdn. But the link I gave shows almost the same code as you wrote.
What you want to do is either to use string.Format:
txtQuestion.Text = string.Format("{0} + {1} = ?", num1, num2);
Or more concise with string interpolation:
txtQuestion.Text = $"{num1} + {num2} = ?";
And show the answer like this:
Random random = new Random();
int nextRandom() => random.Next(0, 100);
int num1 = nextRandom();
int num2 = nextRandom();
txtQuestion.Text = $"{num1} + {num2} = {num1 + num2}";
// If you have a method that computes the result you can also call it inside
txtQuestion.Text = $"{num1} + {num2} = {SomeFunction(num1, num2)}";
To fix your random issue, you must create a random instance only once.
class MyClass
{
// Use the same instance of Random.
private Random _random = new Random();
public int RandomNumber()
{
return _random.Next(0, 100);
}
public void DisplayText()
{
int num1 = RandomNumber();
int num2 = RandomNumber();
txtQuestion.Text = $"{num1} + {num2} = {num1 + num2}";
}
}
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.