Reputation: 5
I have made a simple number generator, and I have a question: is it possible for the generator to eject "red", "blue", "green", " yellow" and "white" instead of the numbers 1-5?
namespace zufallsgenerator
{
public partial class Form1 : Form
{
Random r = new Random();
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void btnWhlie_Click(object sender, EventArgs e)
{
int summe = 0, z;
lblAnzeige.Text = " ";
while (summe <= 0)
{
z = r.Next(1, 6);
summe = summe + z;
}
lblAnzeige.Text += summe + "\n";
}
}
}
Upvotes: 0
Views: 468
Reputation: 17185
You could use an enum.
Define something like
enum Color
{
Red,
Green,
Blue
}
Then you can cast your int to this:
Color color = (Color)r.Next(1, 6)
And, if you wish
Text = color.ToString();
Upvotes: 3
Reputation: 1078
Taking Xi Huan's answer, you can make it a bit prettier using an extension method:
public static T Next<T>(this System.Random Random, params T[] List)
{
if(List.Length==0)
return default(T);
return List[Random.Next(0, List.Length)];
}
Then calling it is just:
var r=new System.Random();
var randon_color = r.Next("red", "blue", "green", "yellow", "white");
Upvotes: 1
Reputation: 101032
You could create a simple array and access it with a randomly generated index, e.g.:
var r = new Random();
string[] colors = {"red", "blue", "green", "yellow", "white"};
var random_color = colors[r.Next(colors.Length)];
Upvotes: 11
Reputation: 146
If you get output like 1-5 you could create string[] containing 5 elements
string[] colors = new string[] { "red", "blue", "green", " yellow", "white" }
And instead of retrieving r.Next( 1, 6 )
you could retrieve colors[ r.Next( 0, 5 ) ]
(because string array is 0-indexed, changed the min and max value).
Upvotes: 2
Reputation: 70923
Define an array with the posible desired output values and instead of concatenating summe to text, add YourArrayOfNamedValues[summe]
Upvotes: 0
Reputation: 2221
What I would do is create a list of strings. Then put the random number as i. So like
List<string> list1 = new List<string>{"red", "blue", "green"};
then use your random number like this to call a random element of it. list1[randomNumber]
;
Upvotes: 0