Select random string from given list

2019-03-22 09:28发布

问题:

I am trying to make Java select 1 random string from a given list.

Example of the list of strings:

1153    3494    9509    2   0   0   0   0
1153    3487    9509    2   0   0   0   0
1153    3491    9525    2   0   0   0   0
1153    3464    9513    2   0   0   0   0

Each row is 1 string

The idea is that it selects one, waits a certain period (like 7200 seconds) and replaces the previous string with another random string from the list (could be the same). The loop is sort of infinite.

Does anyone knows how to do this?

Ps. I am pretty much noobie with java :S, so i am afraid just saying i should use an arraylist (for example) wont work :P

回答1:

public static void main(String[] args) throws InterruptedException {
    List<String> my_words = new LinkedList<String>();
    my_words.add("1153 3494 9509 2 0 0 0 0");
    my_words.add("1153 3487 9509 2 0 0 0 0");
    my_words.add("1153 3491 9525 2 0 0 0 0");
    my_words.add("1153 3464 9513 2 0 0 0 0");

    Random rand = new Random();
    while (true) {
        int choice = rand.nextInt(my_words.size());
        System.out.println("Choice = " + my_words.get(choice));
        Thread.sleep(1000);
        int replaceTo = rand.nextInt(my_words.size());          
        System.out.println("Replace to = " + my_words.get(replaceTo));
        my_words.set(choice, my_words.get(replaceTo));          
    }
}


回答2:

If you have a list/array of data and you want to select a random element from the list. The easiest would probably be to generate a random number with the Math.random (http://download.oracle.com/javase/1.4.2/docs/api/java/lang/Math.html) function which is between 0 and the count of your list/array.

You can then create a Thread that runs forever and sleeps for 7200 seconds between executions that generates a new random number and replaces the old variable.

Just watch out for concurrency issues when using Multi-Threading, have a read at http://download.oracle.com/javase/tutorial/essential/concurrency/.

Update (Example):

Java has a list that can be used to add, and remove data as you want. Data can then by extracted by giving the list the index (number) where the data is located in the list.

So you would be creating a list, then generating a random number in the list's range (0 to the size of the list as the max). And then extracting the data from the list by giving the list your random index. A example would be:

List<String> my_words = new LinkedList<String>();
my_words.add("1153 3494 9509 2 0 0 0 0");
my_words.add("1153 3487 9509 2 0 0 0 0");
my_words.add("1153 3491 9525 2 0 0 0 0");
my_words.add("1153 3464 9513 2 0 0 0 0");

//Maybe a loop to load all your strings here...

Random random = new Random(); //Create random class object
int randomNumber = random.nextInt(my_words.size()); //Generate a random number (index) with the size of the list being the maximum
System.out.println(my_words.get(randomNumber)); //Print out the random word

Hope this makes a bit more sense, and on second thought the Random class in java.util . Would be easier to rap your head around.



回答3:

Since you say you're new to Java, this is a complete sample class to select random elements from a string list:

package com.jmcejuela.lab;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;


public class SO {

    static final int SLEEP_TIME = 2 * 1000; //expressed in milliseconds

    static public void main(String[] args) throws InterruptedException {
        List<String> list = new ArrayList<String>();        
        list.add("hi");
        list.add("hello");
        list.add("booya!"); 

        Random rg = new Random();
        String randomElement;
        int listSize = list.size();
        /* No sense in randomizing when the list has 0 or 1 element
         * Indeed rg.nextInt(0) throws an Exception.
         * You should also check, maybe in a method, that the list
         * is not null before calling list.size()
         */
        if (listSize < 2)
            return;

        while(true) {
            randomElement = list.get(rg.nextInt(listSize));
            System.out.println(randomElement);
            Thread.sleep(SLEEP_TIME);
        }
    }   
}

Then, what do you want eventually to accomplish? With a similar code you could set a class variable, for example. Most probably you want to have a separate Thread that runs this code.