How do I display different sayings, based on a random number
How can I display back to the user a basic popup with a saying based on a random number generated. I wanted to use a switch statement, but that just displays all the sayings, ie:
int random = (int) Math.ceil(Math.random() * 5);
switch(random){
case 1:
showToast(this, "Saying 1.");
case 2:
showToast(this, "Saying 2.");
}
etc....
Like I said, this displays all 5 case statements, is there a better way to random generate and开发者_StackOverflow display based on the number, or am I doing it all wrong?
Thanks!
The case
statements inside a switch "fall through" if you don't break
out of them.
It should be like this:
switch(random) {
case 1:
statement;
break;
case 2:
statement;
break;
...
}
The break statement jumps to the next line after the switch statement.
You can also try some thing like
String[] sayings = {"Saying 1.", "Saying 2.", "Saying 3.", "Saying 4.", "Saying 5."};
int random = (int) Math.ceil(Math.random() * 5);
showToast(this, sayings[random]);
and if you have more items then you can prepare the string array dynamically before use.
If there are many sayings... you can also put a .txt file in your assets folder with numerous sayings (one per line), read it and display the saying from a randomly generated line number..
Activity.getAssets().open("sayingsfile.txt");
精彩评论