我是高中环境中的初学者。我目前是一名AP计算机科学专业的学生,我有一个课堂上的项目来创造一个有趣的"活动。我试图制作卡片和甲板课程,以便用它创建不同的游戏,但我不断从我认为的Deck课程中获得NullPointerException运行时错误。有人能指出我为什么我的代码以这种方式表现的方向?这两个课程如下。谢谢!
public class Card{
private String suit, color, name;
private int value;
public Card (){
suit = "Diamond";
color = "Red";
name = "One";
value = 1;
}
public Card(String n, String s, String c, int v){
suit = s;
color = c;
name = n;
value = v;
}
public String getSuit(){
return suit;
}
public void setSuit(String s){
suit = s;
}
public String getColor(){
return color;
}
public void setColor(String c){
color = c;
}
public String getName(){
return name;
}
public void setName(String n){
name = n;
}
public int getValue(){
return value;
}
public void setValue(int v){
value = v;
}
}
public class Deck{
private Card[] decks;
public Deck(){
decks = new Card[52];
for (int i = 0; i<52; i++){
if(i<26){
decks[i].setColor("Red");
}
else{
decks[i].setColor("Black");
}
if(i<13){
decks[i].setSuit("Diamond");
decks[i].setValue(i+1);
}
else if (i<26){
decks[i].setSuit("Heart");
decks[i].setValue(i-13+1);
}
else if (i<39){
decks[i].setSuit("Spade");
decks[i].setValue(i-26+1);
}
else{
decks[i].setSuit("Clover");
decks[i].setValue(i-39+1);
}
}
for(int i=0; i<52; i++){
if(decks[i].getValue() == 1){
decks[i].setName("Ace");
}
else if (decks[i].getValue() == 11){
decks[i].setName("Jack");
}
else if (decks[i].getValue() == 12){
decks[i].setName("Queen");
}
else if (decks[i].getValue() == 13){
decks[i].setName("King");
}
else{
decks[i].setName(changeName(i));
}
}
}
public String changeName(int value){
if (value == 1)
return "One";
else if (value == 2)
return "Two";
else if (value == 3)
return "Three";
else if (value == 4)
return "Four";
else if (value == 5)
return "Five";
else if (value == 6)
return "Six";
else if (value == 7)
return "Seven";
else if (value == 8)
return "Eight";
else if (value == 9)
return "Nine";
else
return "Ten";
}
public void swap(Card[] d){
int rand = (int)(Math.random()*26 + 1);
int rand2 = (int)(Math.random()*26 + 27);
Card temp = decks[rand];
d[rand] = d[rand2];
d[rand2] = temp;
}
public void shuffle(){
for(int i = 0; i<26; i++){
swap(decks);
}
}
public Card getCard(int n){
return decks[n];
}
public int getValue(int n){
return decks[n].getValue();
}
public String getName(int n){
return decks[n].getName();
}
public String getSuit(int n){
return decks[n].getSuit();
}
public String getColor(int n){
return decks[n].getColor();
}
public Card[] getDeck(){
return decks;
}
}
答案 0 :(得分:2)
decks = new Card[52];
此行不会创建一个充满52个Card对象的数组,它会创建一个可容纳52个Card对象的数组。你仍然需要用对象填充它,否则它们将为空。
for(int i = 0; i < decks.length; i++) {
decks[i] = new Card();
}
会解决问题。