-1

我在 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>
4

2 回答 2

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 集合框架并使用类似列表的东西:

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

一旦你有了一个列表,你可以做几件事:

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 将实际修改列表并随机播放元素,因此请注意这一点。

于 2013-01-10T22:25:58.783 回答
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);
于 2013-01-10T22:21:49.863 回答