簡體   English   中英

如何創建一個包含數字數組和字符串數組的隨機類

[英]How can I create a random class that includes an array of number and an array of strings

我正在使用 GUI 按鈕。 當用戶點擊它時,它會隨機得到一個數字或一個詞。 我知道如何只用數字來做,但我不知道如何處理單詞和數字。

int[] numbers = new int[5] { 100, 500, 1000, 5000, 20000};
Random rd = new Random();
int randomIndex = rd.Next(0, 5);
int randomNumber = numbers[randomIndex];
button1.Text = randomNumber.ToString(); 

string一種解決方案是創建一個要顯示的string List ,然后通過Random.Next()獲取隨機數以在該特定index顯示string 就像是:

List<string> words = new List<string> { "Dog", "Cat", "Bird", "Monkey" };
Random rnd = new Random();

... and then in your implementation of the Button Click

int index = rnd.Next(words.Count); //important to limit the random result by the number of the words available
string randomString = words[index]; //Here it is
button1.Text = randomString; 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM