gpt4 book ai didi

java - 集合随机播放方法具有空对象

转载 作者:行者123 更新时间:2023-12-01 06:43:49 24 4
gpt4 key购买 nike

我正在开发一个涉及 Card 对象和 Deck 对象的 Java 项目。当我制作 Deck 时,我有一个 ArrayList,其中包含所有 52 张卡片。但是,当我在 Collections 中使用 shuffle 方法时,四个 Card 对象将变为 null。Card 类工作正常,当我在洗牌方法之前打印出 Deck 时,所有 52 张卡都在那里。一旦我洗牌,我就会得到四个 null 方法。

import java.util.ArrayList;
import java.util.Collections;
public class Deck {
public ArrayList<Card> pack = new ArrayList<Card>();
public int spades = 1;
public int hearts = 1;
public int diamonds = 1;
public int clubs = 1;
public String s = "spades";
public String h = "hearts";
public String cl = "clubs";
public String d = "diamonds";
public Deck(){

}
public void makeDeck()
{
for (int i = 0; i < 14; i++)
{
Card c = null;
if (clubs < 14)
c = new Card ("Clubs", clubs);
clubs++;
pack.add(c);
if (spades < 14)
c = new Card ("Spades", spades);
spades++;
pack.add(c);
if (hearts < 14)
c = new Card ("Hearts", hearts);
hearts++;
pack.add(c);
if (diamonds < 14)
c = new Card ("Diamonds", diamonds);
diamonds++;
pack.add(c);

}
}

public void showDeck()
{
for (int i = 0; i < 52; i++)
{
System.out.println(pack.get(i));
}
}

public String CardNumber (int index)
{
return (pack.get(index).toString());
}

public int Number (int index)
{
return pack.get(index).CNum();
}

public void Shuffle()
{
Collections.shuffle(pack);
}

}

最佳答案

您的 if 语句有缺陷,您需要大括号:

if (clubs < 14) {  // <--
c = new Card ("Clubs", clubs);
clubs++;
pack.add(c);
} // <--

makeDeck 中的其他 if 语句也是如此。

请注意,在 Java 中,如果不包含大括号,则只有 if 之后的第一个语句将包含在其正文中。

例如:

// 1
if (condition)
A
B

相当于

// 2
if (condition) {
A
}
B

代码片段 1 中 AB 之前的空格与确定 if 语句正文中包含的内容无关.

关于java - 集合随机播放方法具有空对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24149187/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com