开发者

Randomly displaying strings

I made a pool of about 20 strings that each display differen开发者_StackOverflow中文版t sayings. I want one of those sayings to display to a text view on random.

I cast an integer as a random 1-20,

int randomNumber5 = (int) Math.ceil(Math.random() * 20);

and created strings named randomString1, randomString2, etc...til it hits 20.

The best way I could think to do this, was assign each string a number between 1 and 20 as a case.

So:

switch(randomNumber5){
  case 1:
    mTheMessage.setText(R.string.randomString1);  
}
  case 2:
    mTheMessage.setText(R.string.randomString2);  

but I feel like there is a better way to do this right?


Use an array or list.

mTheMessage.setText(RandomString[randomNumber]);

Each element of RandomString[] is loaded with a message.


I would say create an array of strings (the sayings) and get the random number to decide which index to access.


Your method would definitely work but if you had to change your requirements to display 100 or 1000 strings, typing 100 or 1000 cases would not too much fun.

I would stuff the strings in an array or list and return the string by the randomly generated index.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜