如何生成随机字符串?
how to generate random strings?
这是我正在使用的一段代码,但是,我想针对我设置的字符串生成随机响应。如何最好地处理这个问题?也许只是为了澄清,我需要随机输出我的 "Hello"、"Good day"、"bye"、"farewell",而不是按照它们列出的顺序。
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");
}
假定 "strings I have set up" 指的是 importantInfo 变量,并且随机响应是该数组中的随机项:select 来自 Random 对象的随机数,并将此值用作字符串的索引大批。
String randomString = importantInfo[random.nextInt(importantInfo.length)];
获取 RandomUtils 的 apache-commons 并调用 nextInt(4)。
还有随机字符串、long 和 float 方法可用。
这是我正在使用的一段代码,但是,我想针对我设置的字符串生成随机响应。如何最好地处理这个问题?也许只是为了澄清,我需要随机输出我的 "Hello"、"Good day"、"bye"、"farewell",而不是按照它们列出的顺序。
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");
}
假定 "strings I have set up" 指的是 importantInfo 变量,并且随机响应是该数组中的随机项:select 来自 Random 对象的随机数,并将此值用作字符串的索引大批。
String randomString = importantInfo[random.nextInt(importantInfo.length)];
获取 RandomUtils 的 apache-commons 并调用 nextInt(4)。
还有随机字符串、long 和 float 方法可用。