我正在尝试初始化我的playingCard.java文件中定义的ArrayList的新实例:
import java.util.ArrayList;
public class PlayingCard
{
public enum Value { Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten,
Jack, Queen, King, Ace}
public enum Suit { Spades, Diamonds, Hearts, Clubs }
private final Value value;
private final Suit suit;
/**
* Constructs a card with specified initial value and suit
* @param value
* @param suit
*/
public PlayingCard(Value value, Suit suit)
{
this.value = value;
this.suit = suit;
}
/**
* Retrieves the value of a card
* @return value
*/
public Value getValue()
{
return value;
}
/**
* Retrieves the suit of the card
* @return suit
*/
public Suit getSuit()
{
return suit;
}
/**
* Custom toString
*@return value and suit as a string.
*/
@Override
public String toString()
{
return "PlayingCard[value=" + value + ", suit=" + suit + "]";
}
/**
* Format method to print out the value and suit of a card.
* @return value and suit as a string.
*/
public String format()
{
return value + " of " + suit + ", ";
}
/*private static final List<PlayingCard> deck = new ArrayList<PlayingCard>();
// Initialize deck
static
{
for (Suit suit : Suit.values())
{
for (Value value : Value.values())
{
deck.add(new PlayingCard(value, suit));
}
}
}*/
}
如果最后12行左右没有注释掉,则代码没有问题。但是我想在一个单独的测试驱动程序中初始化卡座,并在复制代码时收到2个错误。
测试驱动程序当前如下所示:
import java.util.ArrayList;
public class PlayingCardTester
{
public static void main (String[] args)
{
static List<PlayingCard> deck =
new ArrayList<PlayingCard>();
// Initialize deck
static
{
//for ea PlayingCard.Suit suit in PlayingCard.Suit.values()
for (PlayingCard.Suit suit : PlayingCard.Suit.values())
{
for (PlayingCard.Value value : PlayingCard.Value.values())
{
deck.add(new PlayingCard(value, suit));
}
}
}
}
}
我在测试驱动程序的第14行出现错误
static List<PlayingCard> deck = new ArrayList<PlayingCard>();
说这是非法表达。我尝试在语句前使用不同的关键字,并且错误保持不变。
第二个错误是最后一个括号,它说“ null”。
我对使用枚举不熟悉,所以它看起来很简单,我已经忽略了...
最佳答案
您不需要静态方法中的static
声明。
List<PlayingCard> deck = new ArrayList<PlayingCard>();
另外,由于您已经处于静态上下文中,因此无需
Static Block
。参考文献:
Static Initialization Blocks