Java 桥牌游戏的卡类构造函数和格式化toString()问题
有关实例变量的一些信息Java 桥牌游戏的卡类构造函数和格式化toString()问题,java,Java,有关实例变量的一些信息 int rank–持有一个介于2和14(含)之间的数字,表示卡的等级 char suit–持有代表牌套的字符(“C”、“D”、“H”、“S”),代表梅花、钻石、红桃或黑桃中的一种 关于构造函数应该如何工作的信息 -如果等级为11,则表示该卡为“杰克”,即1分 -如果等级为12,则表示该卡为“女王”,即2分 -如果等级为13,则表示该卡为“国王”,即3分 -如果等级为14,则表示该卡为“a”,即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)
AH(4)在toString
函数中仍然返回字符串
/StringBuilder
值。通常我使用带有3个或更多连接的StringBuilder
。由于返回了打印语句,因此出现错误。@覆盖是可选的
toString()函数
测试程序(main.java)
等等,现在发生了什么不该发生的事?或者你只是想知道如何格式化?如果是后者,为什么不使用If语句来检查秩是否高于某个值,如果高于某个值,则打印出卡的名称(Jack、Queen等)。我在toString()上遇到了格式错误,在检查getPoints()时也没有得到任何值;你说“没有任何价值”是什么意思?你会得到什么格式错误?为什么你给点赋值,就好像它已经有了一样?整个过程可以写成points=Math.max(0,秩-10)
no如果
NeedRegard我说过的关于getPoint()的内容,我不确定toString()的格式在哪里
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);
}
}
@Override public String toString()
{
StringBuilder result = new StringBuilder();
result.append("Suit -> ");
result.append(suit);
result.append(", Rank -> ");
result.append(rank);
result.append(", Points -> ");
result.append("(" + points + ")");
return result.toString();
}
public class main {
public static void main(String[] args) {
Card card1 = new Card(11, 'C');
System.out.println(card1);
}
}