简体   繁体   English

从数组列表中选择一个随机元素,然后从Java中的列表中将其删除

[英]Picking a random element from an arraylist and removing it from the list in Java

I am working on a command line type of program that would allow you to play solitaire. 我正在研究一种允许您玩单人纸牌游戏的命令行类型的程序。 I currently have class Deck and class Card . 我目前有Deck Card类 In class Deck i have an ArrayList and two methods - one that creates a deck and one that shuffles it. 在Deck类中,我有一个ArrayList和两个方法-一个创建甲板,另一个将其洗牌。 I need to create a method that deals a card - meaning a method that would pick a random element from an ArrayList and it is gonna erase it from the ArrayList. 我需要创建一个处理卡的方法-这意味着该方法将从ArrayList中选择一个随机元素,然后将其从ArrayList中删除。 When a card is dealt it is not in the ArrayList anymore, i believe. 我认为,发卡时不再在ArrayList中。 Here is the code in my Deck class: 这是我的Deck类中的代码:

public class Deck {
   private ArrayList deck = new ArrayList < Card > ();
   private Random randomGenerator;

}

public Deck() {
 for (Suit s: Suit.values())
  for (Numbers n: Numbers.values()) {
   Card c1 = new Card(n, s);
   deck.add(c1);
   System.out.println(deck);
  }
}
private void printAll() {}
public void shuffle() {
 Collections.shuffle(deck);
}

I'm really having a hard time with creating a method that would erase the dealt element, what i have done so far is pretty much based on the answers of this problem but it is not quite what i need. 我确实很难创建一种方法来擦除所处理的元素,到目前为止,我所做的大部分工作都是基于此问题的答案,但这并不是我真正需要的。 Retrieving a random item from ArrayList 从ArrayList检索随机项

public Card deal(deck) {
    Random rand = new Random();
    Card dealtCard = rand.deck();
    return dealtCard;
}

Could anyone provide any guidance for me on this method? 有人可以为我提供有关此方法的任何指导吗? Please and thank you 谢谢,麻烦您了

Really the entire point of shuffling the deck is to allow you to deal from the top of the deck and get random cards each time. 洗牌的真正要点是让您从牌的顶部发牌并每次都获得随机的牌。 So if the Deck class has: 因此,如果Deck类具有:

private final List<Card> cards = new ArrayList<>();

And you have called Collections.shuffle(cards) then all you need to do to get the top card in the deck is: 并且您已经调用了Collections.shuffle(cards)那么您需要做的就是在甲板上获得最上面的卡片:

public Card deal() {
    return cards.remove(0);
}

You should also have an isEmpty method so that the caller can make sure there are cards left in the deck before calling deal . 你也应该有一个isEmpty方法,使主叫方可以确保有调用之前留在甲板卡deal That's better coding practice than catching the IndexOutOfBoundsException . 这比捕获IndexOutOfBoundsException更好的编码实践。

You could use something like this 你可以用这样的东西

Random rand = new Random();

int randomElement = givenList.get(rand.nextInt(givenList.size()));

I think this link might be useful http://www.baeldung.com/java-random-list-element 我认为此链接可能很有用http://www.baeldung.com/java-random-list-element

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

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