【问题标题】:How can I create a random class that includes an array of number and an array of strings如何创建一个包含数字数组和字符串数组的随机类
【发布时间】:2016-09-23 20:27:53
【问题描述】:

我正在使用 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(); 

【问题讨论】:

  • 你有一个到目前为止你做过的代码吗?似乎您需要 List<string> 来获取随机的 string

标签: c# arrays string random


【解决方案1】:

string 的一种解决方案是创建要显示的stringList,然后通过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; 

【讨论】:

  • @Donald 是的,试试看! ;)
  • 因为无论如何你都要把它作为文本放在一个按钮中,你可以把数字作为字符串放在那个列表中:new List&lt;string&gt; { "Dog", "Cat", "Bird", "Monkey", "100", "500", "1000" };
  • @diynevala 是的,是的。因为Text 最终是string。 ;)
  • @Ian 甚至有充分的理由使用数字作为字符串:如果您碰巧将一个以零开头的数字(例如邮政编码 00100)作为整数,它将显示前面没有零(例如“100”)。
猜你喜欢
  • 2018-04-14
  • 1970-01-01
  • 2011-08-06
  • 1970-01-01
  • 1970-01-01
  • 2016-01-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多