Sapp
Sapp

Reputation: 1803

Randomly displaying strings

I made a pool of about 20 strings that each display different 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?

Upvotes: 0

Views: 173

Answers (3)

Keefu
Keefu

Reputation: 124

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.

Upvotes: 1

ddrace
ddrace

Reputation: 717

Use an array or list.

mTheMessage.setText(RandomString[randomNumber]);

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

Upvotes: 1

ajwood
ajwood

Reputation: 19027

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

Upvotes: 1

Related Questions