簡體   English   中英

如何獲取、返回和刪除數組中的隨機元素?

[英]How to get, return and delete a random element in an array?

如何從數組中獲取、返回和刪除隨機元素以及最有效的方法? 數組代碼如下所示:

String arr[3] = {"Cat", "Dog", "Mouse", "Horse"};

謝謝你的幫助。

編輯

順便說一下,這是一個記憶游戲,所以如果它重復兩次以上,我會毀了游戲。

您可以使用 % 運算符在數組中創建隨機索引。使用 Math.random 獲取小數隨機數並使用它創建隨機索引,如下所示

String[] arr = {"Cat", "Dog", "Mouse", "Horse"};
    int randPos = ((int)(Math.random()*1000))%arr.length;
    String randEl = arr[randPos];
    System.out.println(randEl);

您不能刪除數組的元素。 您所能做的就是將其設置為 null

你可以做 :

 String[] datas = new String[3];
 Random rand = new Random();
 rand.setSeed(System.currentTimeMillis());

 int i = rand.nextInt(datas.length);
 String val = datas[i];
 datas[i] = null;
 return val;

獲取字符串

Random r = new Random();
String arr[3] = {"Cat", "Dog", "Mouse", "Horse"};
String selectedString = arr[r.nextInt(arr.length)];

對於返回,從方法中返回String selectedString

刪除

Random r = new Random();
String arr[3] = {"Cat", "Dog", "Mouse", "Horse"};
arr[r.nextInt(arr.length)] = null

請注意,這不會移動array元素,也不會減少array的長度。

如果您需要這種功能,我建議使用像Arraylist這樣的Collection

您基本上無法從數組中刪除元素。

請按照以下步驟操作:

  1. 將您的數組轉換為 ArrayList

List<String> list = new ArrayList<String>(Arrays.asList(arr));

  1. 獲取索引的串聯數

int randPos = ((int)(Math.random()*1000))%arr.length;

  1. 刪除該索引處的元素

list.remove(randPos);

  1. 將其轉換回字符串數組

arr = list.toArray(new String[0]);

希望這可以幫助 :)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM