gpt4 book ai didi

java - 找不到空指针异常

转载 作者:行者123 更新时间:2023-12-02 10:41:36 24 4
gpt4 key购买 nike

错误发生在此类的最后一行,我试图打印这副牌中第一张牌的编号,但我不太确定为什么。

    public class CardTricks {
public static void main (String[] args){

Deck newdeck = new Deck();
newdeck.construct();
newdeck.shuffle();
System.out.println(newdeck.deck[0].Number);

}
}

这是卡片的类,主要目的是为卡片提供套件属性和数字属性。

public class Card {
String Suite;
int Number;
}

这是牌组类,该类中的函数用于创建牌组并洗牌。

public class Deck {
Card[] deck;

public void construct(){

deck = new Card[52];

String[] possuite = new String[4];
possuite[0] = "Hearts";
possuite[1] = "Diamonds";
possuite[2] = "Clubs";
possuite[3] = "Spades";

int x = 0;

while (x < 4){
String suite = possuite[x];
x++;
int number = 1;
System.out.println(suite);

while (number < 14){
deck[number-1] = new Card();

deck[number-1].Suite = suite;
deck[number-1].Number = number;
number++;
}
}
}

public void shuffle(){
int x;
int y;
int z = 0;

while (z < 10000){
x = (int)(Math.random()*52);
y = (int)(Math.random()*52);
Card a = deck[y];
Card b = deck[x];
deck[x] = a;
deck[y] = b;
z++;
}

}
}

最佳答案

您只需填充套牌中的前 13 个位置,并在每次生成新套件时覆盖它们。

你应该做什么:(请注意,我已将 x++ 移至底部)

    while (x < 4){
String suite = possuite[x];
int number = 1;
System.out.println(suite);

while (number < 14){
int cardPos = (number-1) + (13*x);
deck[cardPos] = new Card();


deck[cardPos].Suite = suite;
deck[cardPos].Number = number;
number++;
}
x++;

关于java - 找不到空指针异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52888956/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com