Select string randomly


I need a way to randomly create a string between some options.

Let's say I have the strings "A" "B" and "C", would it be possible for Java to choose randomly?

asked by anonymous 10.11.2014 / 19:17

4 answers


Just use the shuffle available for use in collections. This method is done to randomly order elements from a collection.

public static void main(String[] args) {
    List<String> letras = Arrays.asList("A", "B", "C");

To create the string if it's a few elements, just do a simple concatenation, otherwise just use a StringBuilder ( understand because StringBuilder is important when there are too many elements to concatenate in string ).

The AP said that we interpreted the question in a wrong way, so the solution to this is to get the first letter of the string generated as Bacco commented below

There is still another solution:

public static void main(String[] args) {
    String letras = "ABC";  
    Random gerador = new Random();  

See running on ideone . And no Coding Ground . Also put it in GitHub for future reference .

10.11.2014 / 19:30

Try to use this function

// Determia as letras que poderão estar presente nas chaves  

Random random = new Random();  

String armazenaChaves = "";  
int index = -1;  
for( int i = 0; i < 9; i++ ) {  
   index = random.nextInt( letras.length() );  
   armazenaChaves += letras.substring( index, index + 1 );  
10.11.2014 / 19:29

Generate a random number with the function random , remove the module and from there form your string.

import java.util.Random;

public class Random1 { 
    public static void main(String[] args) {

        //instância um objeto da classe Random usando o 
        //construtor padrão 
        Random gerador = new Random(); 
        int x = gerador.nextInt();
        String string;
        switch (x%3){
        case 0:
            string = "A";
        case 1:
            string = "B";
        case 2:
            string = "C";
10.11.2014 / 19:29

To select a String among many in an array :

String[] opcoes = { "A", "B", "C", "D", "Z" };
String selecionada = opcoes[new Random().nextInt(opcoes.length)];

To do the same with a list:

List<String> opcoes = Arrays.asList("A", "B", "C", "D", "Z");
String selecionada = opcoes.get(new Random().nextInt(opcoes.size()));
29.10.2015 / 08:25