如何从给定列表中选择一个随机字符串? (JAVA)

时间:2013-01-10 22:14:35

标签: java javascript random

我在JavaScript中做了同样的事情,但我是JavaScript的新手,我不知道如何转换它......:/

<script language="JavaScript">
<!--
var randomString = new Array ();
randomString[0] = "a random string";
randomString[1] = "another random string";
randomString[2] = "another random string";
randomString[3] = "another random string";
randomString[4] = "another random string";
randomString[5] = "another random string";
randomString[6] = "another random string";
randomString[7] = "another random string";
var i = Math.floor(7*Math.random())

document.write(randomString[i]);
//-->
</script>

2 个答案:

答案 0 :(得分:4)

Java中有几个选项。您可以使用String数组完成此处使用的相同策略:

String[] randomString = new String[8];
randomString[0] = "a random string";
randomString[1] = "another random string";
randomString[2] = "another random string";
randomString[3] = "another random string";
randomString[4] = "another random string";
randomString[5] = "another random string";
randomString[6] = "another random string";
randomString[7] = "another random string";
int i = Math.floor(randomString.length * Math.random());

System.out.println(randomString[i]);

另一种选择是使用Java Collections Framework并使用类似List的内容:

List<String> randomStrings = new LinkedList<String>();
randomStrings.add("a random string");
randomStrings.add("another random string");
randomStrings.add("another random string");

有了List,你可以做几件事:

Collections.shuffle(randomStrings);
System.out.println(randomStrings.get(0));

或:

int i = Math.floor(randomStrings.size() * Math.random());
System.out.println(randomStrings.get(i));

Collections.shuffle将实际修改列表并随机播放元素,因此请注意这一点。

答案 1 :(得分:0)

我的Java有点生疏,但这是怎么回事?

List<String> s = new List<String>(); //better than an array, because those are bounded
s.add("this is a string"); // first string
//repeat

int i = new Random().nextInt(s.size()); 
//from 0 - size exclusive, and the array starts at 0, so this is good

String result = s.get(i);