我正在为我的 CS 课程中的二十一点游戏制作一袋纸牌。这个特定的项目需要我创建一个袋子来容纳我的 52 张卡片。请记住,我试图确保每张牌都有 4 种类型,包括 Q、K、J 和 A。我的 main 中不断出现错误:线程“main”中的异常 java.lang.ClassCastException: [Ljava.lang.Object; 不能转换为 [Ljava.lang.Integer; 在 Main.main(Main.java:14)
如果有人可以帮助我让这个包正常运行,将不胜感激。
这是我的代码:
public class Bag<T>
{
T[] cards;
private final int DEFAULT_CAPACITY = 52;
private int numberOfEntries;
public Bag()
{
this.cards = (T[]) new Object[DEFAULT_CAPACITY];
numberOfEntries = DEFAULT_CAPACITY;
}
public int getCurrentSize()
{
return numberOfEntries;
}
public boolean isFull()
{
return numberOfEntries == DEFAULT_CAPACITY;
}
public boolean isEmpty()
{
return numberOfEntries == 0;
}
public boolean add(T newItem)
{
boolean result = true;
if(isFull())
{
result = false;
}
else
{
cards[numberOfEntries] = newItem;
numberOfEntries++;
}
return result;
}
public boolean remove()
{
boolean result = true;
if(numberOfEntries > 0)
{
numberOfEntries--;
}
else
result = false;
return result;
}
public void clear()
{
numberOfEntries = 0;
}
public int getNumOf(T anItem)
{
int count = 0;
for(int i = 0; i < cards.length; i++)
{
if(anItem.equals(cards[i]))
{
count++;
}
}
return count;
}
public boolean contains(T anItem)
{
boolean found = false;
for (int i = 0; !found && (i < numberOfEntries); i++)
{
if(anItem.equals(cards[i]))
{
found = true;
}
}
return found;
}
public T Grab()
{
int random = (int)(Math.random() * DEFAULT_CAPACITY);
if(!isEmpty())
{
cards[random] = null;
numberOfEntries--;
return cards[random];
}
else
return null;
}
public int getFrequencyOf(T anItem)
{
int counter = 0;
for(int i = 0; i < numberOfEntries; i++)
{
if(anItem.equals(cards[i]))
{
counter++;
}
}
return counter;
}
}
public class Main {
public static void main(String[] args)
{
//Accesses the Bag class
Bag<Integer> bag = new Bag<Integer>();
//Sets up 52 cards (13*4). 4 of each type
for (int i = 1; i <= 13; i++)
{
for (int j = 1; j <= 4; j++) {
bag.cards[i*j] = i;
//if the card is an ace and not equal to 1
if(i == 1)
bag.cards[i*j] = 11;
//handles the king, queen, and jack cards
else if (i==11||i==12||i==13)
bag.cards[i*j] = 10;
}
bag.add(1);
}
}
}