随机的颜色序列

Luk*_*oni 1 java

如何选择一张不能重复的图片?

我试过这个:

我使用随机,我想删除所选的图片

String[] picture = { "blue", "white", "red", "yellow" };

   int number_picture1; 

// Random function to find a random picture

   Random ran = new Random();

   number_picture1 = ran.nextInt(picture.length);

System.out.println(picture[number_picture1]);

// There is still posibility to chose the same picture

   int number_picture2; 

   number_picture2 = ran.nextInt(picture.length);

System.out.println(picture[number_picture2]);
Run Code Online (Sandbox Code Playgroud)

ami*_*mit 6

最简单的方法是使用1来存储元素并在其上使用- 然后迭代地获取元素.ListCollections.shuffle()

随机抽样会产生列表的随机排列,因此迭代选择项目会给你相同的概率来选择任何排序,这似乎正是你所追求的.

代码快照:

String[] picture = { "blue", "white", "red", "yellow" };
//get a list out of your array:
List<String> picturesList = Arrays.asList(picture);
//shuffle the list:
Collections.shuffle(picturesList);
//first picture is the first element in list:
String pictureOne = picturesList.get(0);
System.out.println(pictureOne);
//2nd picture is the 2nd element in list:
String pictureTwo = picturesList.get(1);
System.out.println(pictureTwo);
...
Run Code Online (Sandbox Code Playgroud)

(1)从数组中获取列表的最简单方法是使用 Arrays.asList()

  • @LukaToni不要使用`java.awt.List`,你需要使用[`java.util.List`](http://docs.oracle.com/javase/6/docs/api/java/util/ List.html).请参阅此界面的文档. (3认同)