Reputation: 1803
I have a set of strings labeled st1, st2, st3, etc...until st9. I want to have a method that randomly shows one of those strings based off a randomly generated number...could someone please show me how to do this?
Thanks!
Upvotes: 0
Views: 679
Reputation: 11535
If you have a set of strings defined in strings.xml then it will look more like this:
import java.util.Random
Random rand = new Random();
int[] myarray = new int[]{
R.strings.my_string_1,
R.strings.my_string_2,
R.strings.my_string_3,
R.strings.my_string_4
};
int myrand = rand.nextInt(myarray.length-1);
System.out.println(getText(myarray[myrand]));
This assumes that you're doing this in an Activity
where the getText
method is available.
Upvotes: 0
Reputation: 17131
You'll want to place them in an array and access the member of the array that your generated random number tells you to.
Android generally means java so:
import java.util.Random
Random rand = new Random();
String[] myarray = new String[]{st1, st2, st3, st4, st5, st6, st7, st8, st9};
int myrand = rand.nextInt(8);
System.out.println(myarray[myrand]);
Forgive me any minor syntax errors, it's been a while since I've programmed in Java.
Upvotes: 3
Reputation: 38432
put your strings into an array, pick a random integer between zero and the length of the string array, and use the number to index into the array.
Upvotes: 1