最近,我参加了一家公司的面试,他们给了我一个编程问题。这个问题与纸牌堆有关,其中一个方法是洗牌。因此,我写出了以下程序:
/** Shuffle the list of cards so that they are in random order
* @param d Deck of cards*/
public static void shuffle(Deck d)
{
if(d == null)
throw new IllegalArgumentException();
Random randomGenerator = new Random();
List<Card> cards = d.getDeckOfCards(); // cards is basically Linked List.. cards = new LinkedList<Cards>()
for(int i=0;i<cards.size();i++)
{
int randomNumber = randomGenerator.nextInt(52);
Card c1 = cards.remove(randomNumber);
Card c2 = cards.remove(0);
cards.add(0, c1);
cards.add(randomNumber,c2);
}
}
在上述代码中,我抛出了IllegalArgumentException,这是我最怀疑的。在什么情况下应该抛出运行时异常?我们是否应该抛出运行时异常?谢谢
throw new IllegalArgumentException();
吗? - motokuIllegalArgumentException
实际上是一个RuntimeException
。 - Stefan Falk