public class DeckOfCards 
{
private Card[] card;
private Random rand;

DeckOfCards()
{
rand = new Random();
card = new Card[52];


}

public void Shuffle()
{
Vector<Integer> Hearts = new Vector<Integer>(13);
Vector<Integer> Diamonds = new Vector<Integer>(13);
Vector<Integer> Spade = new Vector<Integer>(13);
Vector<Integer> Clubs = new Vector<Integer>(13); for(Integer i = 1; i <= 13; i ++)
{
Hearts.add(i);
Diamonds.add(i);
Spade.add(i);
Clubs.add(i);
}
int j ;
for(int i = 0; i < 52;)
{
j = rand.nextInt(4);
switch(j)
{
case 0:
if(Hearts.isEmpty())
{
continue;
}
else
{
int a = rand.nextInt(Hearts.capacity());
card[i] = new Card("Hearts", Hearts.elementAt(a));
Hearts.removeElementAt(a);
i ++;
break;
}
case 1:
if(Diamonds.isEmpty())
{
continue;
}
else
{
int a = rand.nextInt(Diamonds.capacity());
card[i] = new Card("Diamonds", Diamonds.elementAt(a));
Diamonds.removeElementAt(a);
i ++;
break;
}
case 2:
if(Spade.isEmpty())
{
continue;
}
else
{
int a = rand.nextInt(Spade.capacity());
card[i] = new Card("Spade", Spade.elementAt(a));
Spade.removeElementAt(a);
i ++;
break;
}
case 3:
if(Clubs.isEmpty())
{
continue;
}
else
{
int a = rand.nextInt(Clubs.capacity() - 1);
card[i] = new Card("Clubs", Clubs.elementAt(a));
Clubs.removeElementAt(a);
i ++;
break;
}
}
}
}这个Shuffle()就是用来洗牌的,思路是先从四种花色中选择一种颜色,如果这种色的牌已经发完了,就重新选择一种花色,反之则从可选的牌中随机选择一张牌,并在可选中删除这张牌,直到52张牌都发完为止,可是这个程序总是会报数组越界的异常,进行不下去,还请高手能帮忙看一下,谢谢:)

解决方案 »

  1.   


        int a = rand.nextInt(Hearts.capacity());
    改成
        int a = rand.nextInt(Hearts.size());
    试试。Vector的capacity与其所容纳的元素的数量并不总是一致。
      

  2.   

    /*
    API Sepcification - java.util.Vector: 
    An application can increase the capacity of a vector before inserting a large number of components; this reduces the amount of incremental reallocation. 为了减少执行增加空间操作的次数,在Vector空间不够时,会一次增加原有容量的数量,如果你没有作设置的话。
    */import java.util.*;class TestVectorCap {    public static void main(String[] args) {
            Vector<Integer> hearts = new Vector<Integer>();        System.out.println("default increase: ");        for(Integer i = 1; i <= 15; i ++) {            
                hearts.add(i);
                System.out.print("capacity:\t" + hearts.capacity());
                System.out.println("\tsize:\t" + hearts.size());
            }        System.out.println();        System.out.println("user custom increase: ");        // 设置每次增加1个元素的空间,实际应用中不要这么做。
            Vector<Integer> hearts1 = new Vector<Integer>(10, 1);
            for(Integer i = 1; i <= 15; i ++) {            
                hearts1.add(i);
                System.out.print("capacity:\t" + hearts1.capacity());
                System.out.println("\tsize:\t" + hearts1.size());
            }
        }
    }
      

  3.   

    嗯,明白了,capacity()表明的是容器能储存对象的大小,而size()则是以储存的对象的个数多谢UnAgain:)