完全失去了为什么eclipse会给出这个错误

时间:2015-08-08 11:49:38

标签: java eclipse

我正在从Java复制代码:如何编写第7版。 这是2个类的代码

public class Card {
    private String face; //face of card
    private String suit; // suit of card

    //2 argument constructor initializes card's face and suit
    public Card(String cardFace, String cardSuit)
    {
        face = cardFace;
        suit = cardSuit;
    }

    // return String representation of Card
    public String toString()
    {
        return face + " of " + suit;
    }
 }

哪个好,但是当我开始进入第二堂课时,我得到了奇怪的错误......

import java.util.Random;

public class DeckOfCards
{
    private Card[] deck;
    private int currentCard;
    private static final int NUMBER_OF_CARDS= 52;
    // random number generator
    private static final Random randomNumbers = new Random();

    // constructor fills decks of cards
    String[] faces = { "Ace", "Duece", "Three", " Four", "Five", "Six",      "Seven",  "Eight", "Nine", " Ten", "Jack", "Queen", "King" }; 
    String[] suits = { "Hearts", "Diamonds", "Clubs", "Spades" };

}

它可以正常工作,但是当我添加下一行时,我得到一个错误,说前一行不正确。

deck = new Card [ NUMBER_OF_CARDS];

这些是日食在线上给我的2个错误

String[] suits = { "Hearts", "Diamonds", "Clubs", "Spades" };

Wacthpoint:DeckOfCards [访问和修改] - 套装 - 令牌上的语法错误";",{在此令牌后预期。 为了清楚起见,这些错误在我添加之前不会出现。

2 个答案:

答案 0 :(得分:2)

您必须将该行放在构造函数或方法中:

public DeckOfCards() {
    deck = new Card[NUMBER_OF_CARDS];
    // fill deck cards here, e.g. deck[0] = new Card(faces[0], suits[0]);
}

答案 1 :(得分:-1)

您可以更改变量 deck NUMBER_OF_CARDS 的初始化顺序。

public class DeckOfCards
{
        private static final int NUMBER_OF_CARDS= 52;
        private Card[] deck = new Card [ NUMBER_OF_CARDS];

        private int currentCard;