Select string at random

Asked

Viewed 4,670 times

7

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

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

  • generates a random number takes the module and assigns the number to a string

4 answers

9


Just use the method shuffle() available for use in collections. This method is made to sort randomly elements of a collection.

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

To create the string if there are few elements just make a simple concatenation, otherwise just use a StringBuilder (understand why Stringbuilder is important when there are many elements to concatenate in the string).


AP said we misinterpreted the question, so the solution to this is to take the first letter of string generated as Bacco commented below

There is still another solution:

public static void main(String[] args) {
    String letras = "ABC";  
    Random gerador = new Random();  
    System.out.println(letras.charAt(gerador.nextInt(letras.length())));
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

  • how does this method @bigown work? I don’t know it, because it would be better than my solution? can you please explain? if you want I create a question just for this!

  • 1

    @Joannis has the link with his documentation. He’s better because he’s already ready and doesn’t need to reinvent the wheel. As the name says it randomly shuffles the elements of any collection. Just what the AP wants. The creators of Java probably did the best they could. Yours has an additional drawback that you need to change a more complex code to change or add a value.

  • Valew, (I had not seen the link to the documentation, I’ll take a look) will my vote in favor =D

  • @Joannis notes that her and the other answer are correct (at least it seemed to me), so much so that I voted for them.

  • Yes, I saw, he and I posted almost at the same time, I understood his response too. I just hadn’t understood his because I didn’t know the suffle. (I’m new to java)

  • Thanks for the help @bigowmn , but actually I don’t want to reorder, but rather choose one of the 3 randomly

  • 1

    @user3511983 but it is random the shuffle. Just take the first of them, which will be a random after the shuffle. Shuffle is "shuffle".

  • @user3511983 It seems that was not what you asked. Note that nobody understood this. I’ll put another solution but what Bacco said solves what you want.

  • The second parameter of substring (in the second example) should not be 1, for it represents the end (end index) and not the size (length).

  • @utluiz is true, a lot of language in the head :)

  • Don’t tell me. Each language makes substring different. : D

Show 6 more comments

4

Try using this function

// Determia as letras que poderão estar presente nas chaves  
String letras = "ABCDEFGHIJKLMNOPQRSTUVYWXZ";  

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 );  
}  
System.out.println(armazenaChaves);  

3

Generate a random number with the function random, take out 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";
            break;
        case 1:
            string = "B";
            break;
        case 2:
            string = "C";
            break;
        }
        System.out.println(string);
    }
}

2

To select a String among many in one 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()));

Browser other questions tagged

You are not signed in. Login or sign up in order to post.