Mobasher Sn
Mobasher Sn

Reputation: 11

how to generate a String random

I used an EditText widget where the client can enter information, then I saved several entries in an ArrayList. Now I want to randomly select one of these entries from the ArrayList. How can I select one element from an ArrayList at random?

I have already tried these ways but it crashes when I run it .

String myrandomString = String.valueOf(rand.nextInt(options.size()));

//int myrandomString = rand.nextInt(options.toString().length());

Upvotes: 0

Views: 149

Answers (2)

Dimitar Spasovski
Dimitar Spasovski

Reputation: 2132

If I understood correctly, you already have an ArrayList<String> that contains previously entered strings and when a new string is entered by the user it is appended to this list. What you would like to do is to select a random string from this list. You can use the java.util.Random class to generate a random index from the list and return the word that is positioned on that index. For example, the code bellow will print a random member of the test list on every execution.

Random random = new Random();

List<String> test = Arrays.asList("Text1","Text2","Text3","Text4");
System.out.println(test.get(Math.abs(random.nextInt()) % test.size()));

EDIT

As stated in the comments, replacing the Math.abs(random.nextInt()) % test.size() with random.nextInt(test.size()) will make the code more readable and reduce the chances for generating a lot of duplicates (it will make the number distribution more uniform).

Upvotes: 1

Digvijay Chauhan
Digvijay Chauhan

Reputation: 31

Start by picking a random index within the arrayList size:

int randIdx = new Random().nextInt(arrayList.size());

Then get the String at that index

String randString = arrayList.get(randIdx);

Upvotes: 0

Related Questions