我正在开发一个纸牌计数程序。我已经让主程序在运行,但是当我尝试实现自己的类时,我在第 19 行得到一个 NullPointerException 错误(只要它到达c.getRank
)。
请注意,我首先在导入一个名为的类时创建了我的主程序,该类CardDeck
具有我工作所需的所有功能,但现在我应该创建自己的类来完成完全相同的事情。(请注意,我无权访问导入的CardDeck
类)。
这是主要代码:
import se.lth.cs.ptdc.cardGames.Card;
public class Patiens {
public static void main(String[] args) {
double good = 0;
double bad = 0;
double result = 0;
for (int a = 0; a < 1000000; a++) {
CardDeck deck = new CardDeck();
deck.shuffle();
double fail = 0;
while (deck.moreCards()) {
for (int i = 1; i <= 3 && deck.moreCards(); i++) {
Card c = deck.getCard();
if (i == 1 && c.getRank() == 1) {
fail++;
}
if (i == 2 && c.getRank() == 2) {
fail++;
}
if (i == 3 && c.getRank() == 3) {
fail++;
}
}
}
if (fail >= 1) {
bad++;
}
else{
good++;
}
}
System.out.println("Good: " + good + " Bad: " + bad);
result = good / bad;
System.out.println("Result= " + result);
}
}
它的作用是计算我的套牌成功完成的概率:
它一边数1-2-3、1-2-3,一边抽牌。现在,如果卡片在计数为“1”时恰好是 ACE,则当前牌组将失败。当程序计数“2”等时,等级 2 的卡片也是如此。它完成而不会失败一次的概率是 0.8% 。
这是我正在创建的 CardDeck 类:
import se.lth.cs.ptdc.cardGames.Card;
import java.util.Random;
public class CardDeck {
private Card[] cards;
private int current;
private static Random rand = new Random();
public CardDeck() {
cards = new Card[52];
for(int suit = Card.SPADES; suit <= Card.CLUBS; suit++) {
for (int i = 0; i < 13; i++) {
cards[i * suit] = new Card(suit, i);
}
}
current = 0;
}
public void shuffle() {
Card k;
for(int i = 1000; i > 0; i--) {
int nbr = rand.nextInt(52);
int nbr2 = rand.nextInt(52);
k = cards[nbr2];
cards[nbr2] = cards[nbr];
cards[nbr] = k;
}
}
/**
*Checks for more cards
*/
public boolean moreCards() {
if(current > 51) {
return false;
} else {
return true;
}
}
/**
*Draws the card lying on top.
*/
public Card getCard() {
return cards[current++];
}
}
这是import se.lth.cs.ptdc.cardGames.Card;
如果需要,它是创建卡片的类。
package se.lth.cs.ptdc.cardGames;
public class Card {
public static final int SPADES = 1;
public static final int HEARTS = SPADES + 1;
public static final int DIAMONDS = SPADES + 2;
public static final int CLUBS = SPADES + 3;
private int suit;
private int rank;
public Card(int suit, int rank) {
this.suit = suit;
this.rank = rank;
}
public int getSuit() {
return suit;
}
public int getRank() {
return rank;
}
}
(请注意,我不应该更改上述课程)