我对编程完全陌生,正在尝试用 Java 创建一个扑克程序。
这段代码在 Player 类中,我试图在其中构建一个空手。无论我如何填充数组(使用循环,像这样等),当我尝试调用 hand[1] 或 hand[i] 或其他方法时,Eclipse 都会告诉我有一个空指针。
通常,没有任何编译时错误。但是当我单独构造手中的每张牌时——见下文——编译器会感到不安……
下面是 Player 和 Class 的相关片段。
我究竟做错了什么?我已经搜索了很多,但仍然不明白。
先感谢您!
class Player {
// Sets up a blank card array called "hand"
// with five (0,0) slots for real cards.
private Card[] hand = new Card[5];
private Card hand[0] = new Card(0, 0); // error: syntax error on token "0", delete this token
private Card hand[1] = new Card(0, 0); // error: syntax error on token "1", delete this token
private Card hand[2] = new Card(0, 0); // error: syntax error on token "2", delete this token
private Card hand[3] = new Card(0, 0); // error: syntax error on token "3", delete this token
private Card hand[4] = new Card(0, 0); // error: syntax error on token "4", delete this token
class Card {
// Sets the default suit/number to zero.
// Lucky for me, such a 0-0 Card does not exist.
private int number = 0;
private int suit = 0;
// Constructs the Card itself by giving it a number and suit.
// Numbers/suits can *only* be set here.
public Card(int n, int s) {
// Bound tester for suit/number values.
// Number has to be between 1 and 14 inclusive (Ace low-Ace high).
// Suit has to be between 1 and 4 inclusive (H/C/D/S).
if (n > 0 && n <= 14 && s > 0 && s <= 4) {
number = n;
suit = s;
}