Java2クラスのプロジェクトを開始したばかりで、完全に停止しました。私はこの方法に頭を悩ませることができません。特に、割り当てで他のDATASTRUCTUREメソッドやJavaのシャッフルメソッドをまったく使用できない場合。
したがって、52枚のカードを保持する52個のノードを含むリンクリストをすでに作成したDeck.classがあります。
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枚のカードをシャッフルするようになりましたが、それが行われるたびに、それらを正しい方法でシャッフルすることはできませんでした。1枚のカードが常に繰り返されました。
別の時点で、52枚のカードすべてにwhileループを通過させましたが、1枚のカードを何度も繰り返しました。
だから私は本当に私が間違っていることについていくつかの入力が必要です。コードの終わりに向かって、私のロジックは完全に間違っていると思いますが、それを回避する方法を理解できないようです。