I've started开发者_Python百科 writing some JAVA code and now I want to get a random letter from list of letters given so what should I use for this.
I'll take your question literally:
Random r = new Random(); // Keep this stored as a field
List<Character> l = ...; // initialize this somewhere
char c = l.get(r.nextInt(l.size()));
Depending on several factors (are the letters contiguous, are you resizing the list dynamically), you may be able to use an array, or may not need a collection. See the Random class.
Example:
Random r = new Random(); // Keep this stored as a field
List<Character> l = Arrays.asList('A', 'F', 'O', 'W', 'M', 'I', 'C', 'E');
char c = l.get(r.nextInt(l.size()));
This snippet should be instructive:
import java.util.Random;
public class RandomLetter {
static Random r = new Random();
static char pickRandom(char... letters) {
return letters[r.nextInt(letters.length)];
}
public static void main(String args[]) {
for (int i = 0; i < 10; i++) {
System.out.print(pickRandom('A', 'F', 'O', 'W', 'M', 'I', 'C', 'E'));
}
}
}
See also:
java.util.Random
- Varargs
If you want to do 3 letters at a time, then you can do something like this instead:
import java.util.Random;
public class RandomLetter {
static Random r = new Random();
static char pickRandom(char... letters) {
return letters[r.nextInt(letters.length)];
}
public static void main(String args[]) {
for (int i = 0; i < 10; i++) {
System.out.println("" +
pickRandom("ACEGIKMOQSUWY".toCharArray()) +
pickRandom("BDFHJLNPRVXZ".toCharArray()) +
pickRandom("ABCDEFGHJKLMOPQRSTVWXYZ".toCharArray())
);
}
}
}
精彩评论