我刚刚为我的 Java2 类启动了一个项目,但我已经完全停止了。我只是无法理解这种方法。尤其是当分配不允许我们使用任何其他 DATA STRUCTURE 或 java 中的 shuffle 方法时。
所以我有一个 Deck.class 我已经在其中创建了一个包含 52 个节点的链表,其中包含 52 张卡片。
public class Deck {
private Node theDeck;
private int numCards;
public Deck ()
{
while(numCards < 52)
{
theDeck = new Node (new Card(numCards), theDeck);
numCards++;
}
}
public void shuffleDeck()
{
int rNum;
int count = 0;
Node current = theDeck;
Card tCard;
int range = 0;
while(count != 51)
{
// Store whatever is inside the current node in a temp variable
tCard = current.getItem();
// Generate a random number between 0 -51
rNum = (int)(Math.random()* 51);
// Send current on a loop a random amount of times
for (int i=0; i < rNum; i ++)
current = current.getNext(); ******<-- (Btw this is the line I'm getting my error, i sort of know why but idk how to stop it.)
// So wherever current landed get that item stored in that node and store it in the first on
theDeck.setItem(current.getItem());
// Now make use of the temp variable at the beginning and store it where current landed
current.setItem(tCard);
// Send current back to the beginning of the deck
current = theDeck;
// I've created a counter for another loop i want to do
count++;
// Send current a "count" amount of times for a loop so that it doesn't shuffle the cards that have been already shuffled.
for(int i=0; i<count; i++)
current = current.getNext(); ****<-- Not to sure about this last loop because if i don't shuffle the cards that i've already shuffled it will not count as a legitimate shuffle? i think? ****Also this is where i sometimes get a nullpointerexception****
}
}
}
现在,当我调用此方法时,会出现不同类型的错误:
它有时只会洗 2 张牌,但有时会洗 3 - 5 张牌,然后给我一个 NullPointerException。我已经在上面的代码中用星号指出了它在哪里给了我这个错误
有一次我让它洗了 13 张牌,但每次洗牌时都没有以正确的方式洗牌。一张牌一直在重复。
在另一点上,我让所有 52 张卡片都通过了 while 循环,但它又多次重复了一张卡片。
所以我真的需要一些关于我做错了什么的意见。在我的代码结束时,我认为我的逻辑完全错误,但我似乎无法找到解决方法。