我得到了一个String[]
,我想从中获取一个随机值。我尝试将这种逻辑放入另一种方法中。这是我到目前为止的代码。
public static void main(String[]args) {
String [] S = {"aaa", "bbb", "ccc", "ddd", "eee","ggg", "hhh", "iii", "kkk"};
}
public String get () {
int i;
for(i = 0; i <= 4; i++) {
}
}
我需要使用 get()
方法从数组 S
中随机获取字符串,但我真的不知道该怎么做。
最佳答案
首先,您必须将 S 数组移动为实例变量或静态变量,因为目前它是您的 main 方法的本地变量,无法从您的 get
方法访问。
然后你可以这样得到一个随机字符串:
private Random rnd = new Random();
public String get ()
{
return S[rnd.nextInt(S.length)];
}
关于java - 如何从字符串数组中获取随机字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26698043/