我有一项任务,我遇到了麻烦。重点是让程序打印出具有二十一点值的卡片。它不需要实际添加卡,而只需显示卡的名称和值。
我的麻烦在于显示ace,king,queen和jack之后的数字。我的代码是
import static java.lang.System.*;
public class Card
{
public static final String FACES[] = {"ZERO","ACE","TWO","THREE","FOUR",
"FIVE","SIX","SEVEN","EIGHT","NINE","TEN","JACK","QUEEN","KING"};
//instance variables
private String suit;
private int face;
//constructors
public Card( String s, int f)
{
suit = s;
face = f;
}
// modifiers
public void setFace( int f)
{
face = f;
}
public void setSuit( String s)
{
suit = s;
}
//accessors
public String getSuit()
{
return suit;
}
public int getFace()
{
return face;
}
//toString
public String toString()
{
return FACES[face] + " of " + suit;
}
}
import static java.lang.System.*;
import java.awt.Color;
public class CardRunner
{
public static void main( String args[] )
{
Card one = new Card("SPADES", 9);
out.println(one.getSuit());
out.println(one.getFace());
Card two = new Card("DIAMONDS", 1);
out.println(two);
two.setFace(3);
out.println(two);
Card three = new Card("CLUBS", 4);
out.println(three);
Card four = new Card("SPADES", 1);
out.println(four);
Card five = new Card("HEARTS", 13);
out.println(five);
Card six = new Card("HEARTS", 11);
out.println(six);
Card seven = new Card("CLUBS", 12);
out.println(seven);
}
}
我在想我会添加一个调用super(s,f)的方法,因为这就是我们正在学习的内容,而赋值的方法是使用super调用。我只是在显示数字时遇到了麻烦。
我的输出是:
SPADES
9
ACE of DIAMONDS
THREE of DIAMONDS
FOUR of CLUBS
ACE of SPADES
KING of HEARTS
JACK of HEARTS
QUEEN of CLUBS
我需要的输出是:
SPADES
9
ACE of DIAMONDS
THREE of DIAMONDS
FOUR of CLUBS
ACE of SPADES 11
KING of HEARTS 10
JACK of HEARTS 10
QUEEN of CLUBS 10
答案 0 :(得分:1)
只需存储卡的实际值的另一个变量。
注意:我会实现getValue()
而不是getFace()
来返回卡的“正确”值而不是数组的索引。
//instance variables
private String suit;
private int face;
private int value;
//constructors
public Card( String s, int f)
{
suit = s;
face = f;
value = f; // This handles 2..10
if (f > 10) value = 10; // Face values are all 10
if (f == 1) value = 11; // Ace. Remove if 1 and 11 should be different
}
public String toString()
{
String s = FACES[face] + " of " + suit;
if (face > 10 || face == 1) {
s += " " + value;
}
return s;
}