当前位置: 动力学知识库 > 问答 > 编程问答 >

java - how to get those array values randomly?

问题描述:

I have the following string array:

String arry[] = { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J",

"K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V",

"W", "X", "Y", "Z", "a", "b", "c", "d", "e", "f", "g", "h",

"i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t",

"u", "v", "w", "x", "y", "z", "0", "1", "2", "3", "4", "5",

"6", "7", "8", "9", "`", "~", "!", "@", "#", "$", "%", "^",

"&", "*", "(", ")", "-", "_", "=", "+", ";", ":", "'", "|", "",

"<", ",", ">", ".", "/", "?", };

In this String array how to get a values randomly ?

For example:

AG.4fF

h9_wO4

So far, I have the following code:

for (String st : arry) {

String randomValue = arry[new Random().nextInt(arry.length)];

System.out.println(" Inside array values :-->> " + randomValue);

}

For this code, it returns all the array values, then how to form a multiple combinations.

as i mentioned earlier?

网友答案:

To get a String of characters you can do

static final String chars = 
               "ABCDEFGHIJKLMNOPQRSTUVWXYZ" +
               "abcdefghijklmnopqrstuvwxyz" +
               "0123456789`[email protected]#$%^&*()-_" +
               "=+;:'|\"<,>./?";

static final Random rand = new Random();
public static String randString(int length) {
     char[] gen = new char[length];
     for (int i = 0; i < length; i++) 
          gen[i] = chars.charAt(rand.nextInt(chars.length));
     return new String(gen);
}
网友答案:

Do you mean generating random string from this set of characters? You can perform it in this way:

int len = ...; // length of resulting string
StringBuilder builder = new StringBuilder();
Random rand = new Random();
for (int i = 0; i < len; ++i) {
    String c = arry[rand.nextInt() % arry.length];
    builder.append(c);
}
String str = builder.toString();
网友答案:
import java.util.Random;

...

Random random = new Random(); // Step 1 - creating random object
System.out.println(arry[random.nextInt(arry.length)]); // Step 2

In step 2. we generate random number within range of 0 to arrays length than get element reside

Random.nextInt(int n) method returns pseudorandom, uniformly distributed int value between 0 (inclusive) and the specified value (exclusive)

分享给朋友:
您可能感兴趣的文章:
随机阅读: