数组中的随机数组-Java

数组中的随机数组-Java,java,arrays,random,Java,Arrays,Random,我有一个数组:{红,蓝,绿}。我想生成另一个随机包含ex:{red,red,blue,green,blue}的数组。我想使用一个可变长度的随机数组。下面是一个如何将随机数组与数组一起使用的示例: public static void main(String[] args) { String colors[] = {"red", "blue", "green"};//your array of colors int n = 10;//number of element you wa

我有一个数组:{红,蓝,绿}。我想生成另一个随机包含ex:{red,red,blue,green,blue}的数组。我想使用一个可变长度的随机数组。

下面是一个如何将随机数组与数组一起使用的示例:

public static void main(String[] args) {
    String colors[] = {"red", "blue", "green"};//your array of colors
    int n = 10;//number of element you want to make in your new array
    String random[] = new String[n];
    for(int i = 0; i< n; i++){
        //add values with random values of the colors array
        random[i] =  colors[new Random().nextInt(colors.length)];
    }
    System.out.println(Arrays.toString(random));//print the random array
}
伪代码:

colours <- {red, blue, green}
length <- random (0 to maxLength)
repeat length times
  colour <- pick random from colours
  append colour to outputArray
end repeat
return outputArray

颜色您可以尝试以下方法:

import java.util.ArrayList;
import java.util.Random;

public class RandomArrayTest {

    public static void main(String[] args) {

        System.out.println(RandomArrayTest.randomArrayOfColors(10)); // for example

    }

    public static ArrayList<String> randomArrayOfColors(int lenOfArray){
        String[] colors = {"RED", "GREEN", "BLUE"};
        ArrayList<String> rndArray = new ArrayList<String>();
        Random rnd = new Random();
        for(int i=0; i<lenOfArray; i++){ // populate the array
            rndArray.add(colors[rnd.nextInt(colors.length)]);
        }

        return rndArray;    
    }
}

请阅读并考虑提供一个感谢!像charmyou一样工作欢迎…@StringDot如果您对代码有任何疑问,请不要犹豫
import java.util.ArrayList;
import java.util.Random;

public class RandomArrayTest {

    public static void main(String[] args) {

        System.out.println(RandomArrayTest.randomArrayOfColors(10)); // for example

    }

    public static ArrayList<String> randomArrayOfColors(int lenOfArray){
        String[] colors = {"RED", "GREEN", "BLUE"};
        ArrayList<String> rndArray = new ArrayList<String>();
        Random rnd = new Random();
        for(int i=0; i<lenOfArray; i++){ // populate the array
            rndArray.add(colors[rnd.nextInt(colors.length)]);
        }

        return rndArray;    
    }
}
[GREEN, GREEN, BLUE, GREEN, RED, BLUE, GREEN, RED, RED, BLUE]