这是我正在使用的一段代码,但是,我想针对我设置的字符串生成随机响应。如何最好地处理这个问题?也许只是为了澄清,我需要随机输出我的“你好”、“美好的一天”、“再见”、“告别”,而不是它们列出的顺序。
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");
}
最佳答案
假设“我已设置的字符串”指的是 importantInfo 变量,随机响应是该数组中的随机项:从 Random 对象中选择一个随机数,并将该值用作字符串数组的索引。
String randomString = importantInfo[random.nextInt(importantInfo.length)];
关于java - 如何生成随机字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29237517/