从给定列表中选择随机字符串

我试图让Java从给定列表中选择1个随机字符串。

字符串列表示例:

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 

每行是1个字符串

这个想法是它选择一个,等待一段时间(如7200秒)并用列表中的另一个随机字符串替换前一个字符串(可能是相同的)。 循环有点无限。

有谁知道怎么做?

PS。 我非常喜欢java:S,所以我只是说我应该使用arraylist(例如)不会工作:P

 public static void main(String[] args) throws InterruptedException { List my_words = new LinkedList(); 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)); } } 

如果您有一个列表/数组数组,并且您想从列表中选择一个随机元素。 最简单的可能是使用Math.random(http://download.oracle.com/javase/1.4.2/docs/api/java/lang/Math.html)函数生成一个随机数,该函数介于0和0之间。列表/数组的计数。

然后,您可以创建一个永久运行的线程,并在生成新随机数的执行之间hibernate7200秒并替换旧变量。

在使用multithreading时请注意并发问题,请阅读http://download.oracle.com/javase/tutorial/essential/concurrency/ 。

更新(示例):

Java有一个列表,可用于添加和删除数据。 然后可以通过向列表提供数据在列表中所在的索引(数字)来提取数据。

因此,您将创建一个列表,然后在列表的范围内生成一个随机数(0到列表的大小为最大值)。 然后通过给列表提供随机索引从列表中提取数据。 一个例子是:

 List my_words = new LinkedList(); 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 

希望这更有意义,第二个想到java.util中的Random类。 更容易说出你的头脑。

既然您说您是Java新手,那么这是一个完整的示例类,用于从字符串列表中选择随机元素:

 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 list = new ArrayList(); 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); } } } 

那么,你最终想要完成什么? 例如,使用类似的代码可以设置类变量。 很可能你想拥有一个运行这段代码的独立线程。