【发布时间】:2015-05-01 01:10:23
【问题描述】:
关于实例变量的一些信息。
int rank - 包含 2 到 14(含)之间的数字,表示卡片的等级
char suit - 包含一个代表卡片花色的字符('C'、'D'、'H'、'S'),代表梅花、方块、红心或黑桃之一。
关于构造函数应该如何工作的信息。
-如果点数为11,则表示该牌是“J”,即1分。
-如果等级是12,那意味着这张牌是“女王”,也就是2分。
-如果点数为13,则表示该牌是“王”,即3分。
-如果点数是 14,则表示这张牌是“ace”,即 4 点。
-任何其他卡都值 0(零)分。
然后是关于 toString() 应该如何工作的一些信息。
应该采用简单的格式,例如这些示例。
AH (4) <-Ace of Hearts (worth 4 points)
KC (3) <-King of Clubs (worth 3 points)
QD (2) <-Queen of Diamonds (worth 2 points)
JC (1) <-Jack of Clubs (worth 1 point)
10S (0) <-10 of Spades (worth 0 points)
9D (0) <-9 of Diamonds (worth 0 points)
如你所见,这个String应该使用2个位置来表示排名(如果不是10,则需要以空格字符开头),然后是花色字符,然后是另一个空格,最后是高数- 括号中的值。
以下是我遇到问题的代码的当前布局。
public class Card
{
//Holds rank of the card
private int rank;
//Holds suit of the card character
private char suit;
//Holds the number of high-card points
private int points;
/**
* Constructor to check rank and points
*/
public Card(int rank, char suit)
{
//Initialise instance variables
this.rank = rank;
this.suit = suit;
if (rank > 1 && rank < 15) {
if (rank == 11)
points++;
else if (rank == 12)
points += 2;
else if (rank == 13)
points += 3;
else if (rank == 14)
points += 4;
else
points += 0;
}
}
/**
* Gets the rank value
*/
public int getRank()
{
return rank;
}
/**
* Gets the suit
*/
public char getSuit()
{
return suit;
}
/**
* Gets the points
*/
public int getPoints()
{
return points;
}
/**
* String with values of rank,suit,points to be formatted
*/
public String toString()
{
return System.out.printf("%2d %4s %6d", rank, suit, points);
}
}
【问题讨论】:
-
等等,现在发生了什么不应该发生的事情?或者您只是想知道如何进行格式化?如果是后者,为什么不使用 if 语句来检查等级是否高于某个值,如果是,则打印出卡片的名称(Jack、Queen 等)
-
我在 toString() 上收到格式错误,并且我在检查 getPoints() 时也没有得到任何值;
-
你“没有得到任何价值”是什么意思?你得到什么格式错误?
-
你为什么要给点赋值,就好像它已经有了一样?整个事情可以写成
points = Math.max(0, rank - 10);noifneeded -
关于我所说的 getPoint(),我不知道去哪里格式化 toString()
标签: java