2

I've started 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.

Jim Ferrans
  • 30,582
  • 12
  • 56
  • 83
Ivan
  • 29
  • 1
  • 3

2 Answers2

6

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()));   
Matthew Flaschen
  • 278,309
  • 50
  • 514
  • 539
  • I can't compile the code above can you give me a sample, for example random letter from A F O W M I C E – Ivan Mar 20 '10 at 05:40
  • @Ivan You can't compile it because you need to initialize the list. After that, it will compile, so just add the characters that you want to the list. – Kevin Crowell Mar 20 '10 at 05:49
1

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:


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())
         );
      }
   }   
}
polygenelubricants
  • 376,812
  • 128
  • 561
  • 623