我正在從oracle的網站上學習Java和OOPS。我在做this exercise。Java代碼中的NullPointerException
當我運行此代碼時,出現空指針異常。有人可以向我解釋我做錯了什麼嗎?
Card.java
public class Card {
public enum Suits {
SPADE,
CLUB,
DIAMOND,
HEART
}
public enum Ranks {
Ace,
DEUCE,
THREE,
FOUR,
FIVE,
SIX,
SEVEN,
EIGHT,
NINE,
TEN,
JACK,
QUEEN,
KING
}
public Ranks rank;
public Suits suit;
public Card(Card.Ranks rank,Card.Suits suit) {
this.rank=rank;
this.suit=suit;
}
}
Deck.java
import java.util.*;
public class Deck {
public ArrayList<Card> cards;
private Card card;
public Deck() {
for(Card.Suits s: Card.Suits.values()) {
for(Card.Ranks r:Card.Ranks.values()) {
card=new Card(r,s);
cards.add(card);
}
}
}
}
DisplayCards.java
public class DisplayCards {
public static void main(String [] args) {
Deck d=new Deck();
for(Card c: d.cards) {
System.out.println("Rank of the Card:"+c.rank.toString());
System.out.println("Suit of the Card:"+c.suit.toString());
}
}
}
嘗試將異常堆棧跟蹤粘貼到問題中。這通常是開始診斷此類問題的最佳方法。 –
如果你確切地說是你得到這個NPE,它可能會加快速度。刪除空行也不會傷害。 –
我很抱歉沒有提出異常。 – gizgok