从给定列表中选择随机字符串 [英] Select random string from given list

查看:171
本文介绍了从给定列表中选择随机字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

字符串列表示例:

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秒)并用列表中的另一个随机字符串替换前一个字符串(可能是相同的)。
循环有点无限。

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.

有谁知道怎么做?

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

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

推荐答案

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));          
    }
}

这篇关于从给定列表中选择随机字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆