开发者

How to get a random letter from a list of specific letters?

开发者 https://www.devze.com 2022-12-23 07:08 出处:网络
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:

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())
         );
      }
   }   
}
0

精彩评论

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