18

I have list of countries in my array, I would like to pick random country from the list (using random probably?), but I haven't found out the answer myself...

This is what I have so far:

String[] list = {"Finland", "Russia", "Latvia", "Lithuania", "Poland"};
Random r = new Random();
0

8 Answers 8

38

Try:

list[r.nextInt(list.length)];
Sign up to request clarification or add additional context in comments.

3 Comments

@roni: Burleigh Bear is correct, the value will never be list.length. As per the Java documentation: "Returns a pseudorandom, uniformly distributed int value between 0 (inclusive) and the specified value (exclusive)"
@Burleigh Bear Can you please tell me how can I choose a random string from that array and also I want some other string every time. I mean if I don't want to repeat the string value what's modification I need in this code .
The usual way to do that is to permute the list (i.e. do a shuffle - you can look up Knuth's algorithm for this). Then you can just iterate through the list to return each item successively.
5

The accepted answers is not working for me the solution worked for me is

List<String> myList = Arrays.asList("A", "B", "C", "D");

Suppose you have this above ArrayList and you want to randomize it

    Random r = new Random();

    int randomitem = r.nextInt(myList.size());
    String randomElement = myList.get(randomitem);

If you print this randomElement variable you will get random string from your ArrayList

Comments

2
static String getRandomString(){
        int r = (int) (Math.random()*5);
        String name = new String [] {"India","USA","UK","Russia"}[r];
        return name;
    }

1 Comment

If you have 4 strings in the array, you should use int r = (int) (Math.random()*4);
1

Ran into a similar problem with pulling a random string from a string array. Found this to work fairly well, I applied it to a button action so with every click a random is drawn(I found with any array size there are multiple instances of the same string being drawn consecutively throughout):

import java.util.*;
import java.util.Random.*;

class Countries {
    public Random g2 = new Random();
    public String[] list = new String[] { "Finland", "Russia",
            "Latvia", "Lithuania", "Poland" };
    String random2;
}

// Applied to a button action:
int INDEXn = g2.nextInt(list.length);
for (int i2 = 0; i2 < INDEXn; i2++) {
    random2 = (String) (list[INDEXn]);
}
System.out.println(random2 + '\n');

The g2 random that is being used by INDEXn is calling a random integer, in this case the defined strings are turned into integer values, from the String array list. The for-loop is cycling through the String array one time. The random2 string is converting the chosen integer from INDEXn to the appropriate string variable in (list[INDEXn]).

Comments

0
private void pickText(){ 
    textview textView1= (TextView) findViewById(R.Id.textView1)
    Random eventPicker = new Randorn();
    randomN = eventPicker.nextInt(3) +1; 

    switch (randomN){ 
        case 1: Intent a textview1.setText(StringOne);
        break; 

        case 2: textview1.setText(StringTwo);
        break; 

I typed it from my phone there's prob syntax errors but it works.

Comments

0
list[Math.floor(r.nextFloat()*5.99)]

4 Comments

because of the floor. you will not get a uniform distribution as 5 will only be the result when getFloat returns 1.0.
But there is only 5 entries so you want a uniform distribution for 0..4 not 5.
Why floor a float rather than just using an integer?
4.99 will means there is slightly less chance of getting 4 as the rest, why not 5?
0

Here's a solution in 1 line:

String country = new String[] {"Finland", "Russia", "Latvia", "Lithuania", "Poland"}[(int)(Math.random()*5)];

Comments

-1

import java.util.Random; public static void main (String [] args){

// For this code, we are trying to pic a random day from days

String [] days = {"Sunday","Monday",
            "Tuesday",
            "Wednesday",
            "Thursday",
            "Friday",
            "Saturday"};

Random rand = new Random();

int Rand_item = rand.nextInt(days.length);

System.out.println(days[Rand_item]);

}

1 Comment

Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.