简体   繁体   English

如何从字符串数组中获取随机字符串?

[英]How to get a random string from an array of strings?

I got a String[] from which I want to get a random value. 我有一个String[] ,我想从中获得一个随机值。 I try to put that logic in another method. 我尝试将该逻辑放在另一种方法中。 This is my code so far. 到目前为止,这是我的代码。

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++) {

    }
}

I need random strings out of array S with the method get() , but I really don't know how to do it. 我需要使用方法get()从数组S取出随机字符串,但我真的不知道该怎么做。

First you'll have to move the S array to be an instance variable or a static variable, because currently it's local to your main method, and can't be accessed from your get method. 首先,您必须将S数组移动为实例变量或静态变量,因为当前它在您的main方法中是本地的,并且无法从get方法中访问。

Then you can get a random String this way : 然后,您可以通过以下方式获取随机String:

private Random rnd = new Random();
public String get ()
{
   return S[rnd.nextInt(S.length)];
}

You can use java.util.Random to generate random things. 您可以使用java.util.Random生成随机的东西。 However, keep in mind that, it is not secure, not really random. 但是,请记住,它不是安全的,不是真正随机的。

You can get random char s from the array S : 您可以从数组S获取随机char

String randomString = ""; 
Random rand = new Random();
for(int i=0;i<=4;i++)
{
    randomString += S[rand.nextInt(S.length())].charAt(0);
}

System.out.println(randomString);

you do not need loop in get() method you need to generate a random number below the length of the original array and say return S[RANDOM_NUMBER] 您不需要在get()方法中循环,您需要在原始数组的长度以下生成一个随机数,然后说return S [RANDOM_NUMBER]

EDIT 编辑

let the get method takes a parameter of String[] 让get方法采用String []的参数

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM