我正在努力完成任务,目前难以解决我的问题。我已阅读了几篇文章并试图解决但没有成功。我知道我的很多代码都可以简化,但这是文本的进展所以很多东西还没有被覆盖......
这是我的卡类
import java.util.Random;
public class Card {
private int suit,face;
private String cardS,cardF;
// Default constructor to generate random number for face and suit
public Card()
{
Random rand = new Random();
suit = rand.nextInt(4)+1;
face = rand.nextInt(13)+1;
}
// Receive card and suit values
public Card(int cardSuit, int cardFace) {
suit = cardSuit;
face = cardFace;
// Define card face and suit values
if(suit == 1){
cardS = "Clubs";
}
else if(suit == 2){
cardS = "Hearts";
}
else if(suit == 3){
cardS = "Spades";
}
else if(suit == 4){
cardS = "Diamonds";
}
if(face == 1){
cardF = "Ace";
}
else if(face == 2){
cardF = "2";
}
else if(face == 3){
cardF = "3";
}
else if(face == 4){
cardF = "4";
}
else if(face == 5){
cardF = "5";
}
else if(face == 6){
cardF = "6";
}
else if(face == 7){
cardF = "7";
}
else if(face == 8){
cardF = "8";
}
else if(face == 9){
cardF = "9";
}
else if(face == 10){
cardF = "10";
}
else if(face == 11){
cardF = "Jack";
}
else if(face == 12){
cardF = "Queen";
}
else if(face == 13){
cardF = "King";
}
//return cardF + " of " + cardS;
}
// Get numerical face value
public int getNumericFace(){
return face;
}
// Get numerical suit value
public int getNumericSuit(){
return suit;
}
}
这是我的DeckOfCards类
public class DeckOfCards {
public static final int MAXDECK = 52;
int remainingDeck,suit,face;
String cardS,cardF;
private int myCard;
int cardIndex;
Card[] cardDeck;
public DeckOfCards() {
cardDeck = new Card[MAXDECK];
// Create array of 52 cards
// outer loop cardSuit
// inner loop cardFace
int index = 0;
int maxSuit = 4;
int maxFace = 13;
for (int cardSuit = 1 ; cardSuit <= maxSuit ; cardSuit++)
{
for (int cardFace = 1 ; cardFace <= maxFace ; cardFace++)
{
cardDeck[index] = new Card(cardSuit,cardFace);
index++;
}
}
}
public String getArray()
{
System.out.println(cardDeck[0]);
for (int i = 0 ; i < cardDeck.length ; i++)
{
System.out.println(cardDeck[i]);
}
return "";
}
public String toString()
{
String deckAsString = "";
int i=0;
for (int s = 1; s <= 4 ; s++)
{
for (int c = 1 ; c <= 13 ; c++ )
{
deckAsString += (cardDeck[i] + "");
i++;
}
deckAsString += "\n";
}
return (deckAsString);
}
}
这是我的主要课程......在这里运行这两种方法都存在问题。
public class MainDeck {
public static void main(String[] args) {
DeckOfCards game = new DeckOfCards();
System.out.println("test getArray method");
System.out.println(game.getArray());
System.out.println("test toString method");
System.out.println(game.toString());
}
}
感谢您的帮助!
答案 0 :(得分:0)
因为DeckOfCards中的toString方法正在使用cardDeck数组对象并将它们添加到返回的String中:
deckAsString += (cardDeck[i] + "");
所以你需要覆盖toString
类中的Card
方法,并在字符串操作中使用它。
答案 1 :(得分:0)
请在toString()
课程中实施Card
方法。