如何生成随机字符串?

时间:2015-03-24 16:06:46

标签: java string random

这是我正在使用的一段代码,但是,我想生成关于我设置的字符串的随机响应。如何最好地接近这个?也许只是为了澄清,我需要随机输出“Hello”,“Good day”,“bye”,“告别”,而不是列出它们的顺序。

public void run() {
    String importantInfo[] = {
          "Hello",
          "Good day",
          "bye",
          "farewell"
    };

    Random random = new Random();

    for (int i = 0; i < importantInfo.length; i++) {
        drop.put(importantInfo[i]);
        try {
            Thread.sleep(random.nextInt(5000));
        } catch (InterruptedException e) {}
    }
    drop.put("DONE");
}

2 个答案:

答案 0 :(得分:7)

假设&#34;我设置的字符串&#34;指的是importantInfo变量,随机响应是该数组中的随机项:从Random对象中选择一个随机数,并使用该值作为字符串数组的索引。

String randomString = importantInfo[random.nextInt(importantInfo.length)];

答案 1 :(得分:2)

获取RandomUtils的apache-commons并调用nextInt(4)。

还有随机的字符串,长整数和浮点方法。

相关问题