-1
我是高中環境中的初學者編碼員。我目前是一名AP計算機科學學生,我有一個課堂項目來創建一個「有趣」的活動。我試圖製作一個Card和Deck類來創建不同的遊戲,但是我一直從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;
}
}