문제

I'm trying to make a card game, and have my card class and my deck class sort of ready, it compiles ok, but when I try to run deck's method makeDeckFull, i get the output: invalidnumberinvalidnumber...

when I use the showDeck method I then see this instead of "hearts", 1 Cards@597f13c5 (i do not know what it means, or how to fix it)

Any help would be kindly appreciated: code below.

Deck Class:

import java.util.ArrayList;
public class Deck
{
    private ArrayList<Cards> deck;
    private int index;

    public Deck()
    {
        deck = new ArrayList<Cards>();
    }

    public void makeDeckFull()
    {
        Cards h1 = new Cards("Hearts", 1);
        Cards h2 = new Cards("Hearts", 2);
        Cards h3 = new Cards("Hearts", 3);
        deck.add(h1);
        index ++;
        deck.add(h2);
        index ++;
        deck.add(h3);
        index ++;
        //Rest of these is left out to conserve space
    }

    public void showDeck()
    {
        System.out.println(deck); 
    }

Card class:

public class Cards
{
    private String HEARTS = "Hearts";
    private String CLUBS = "Clubs";
    private String DIAMONDS = "Diamonds";
    private String SPADES = "Spades";
    public int number;
    public String suit;
    public Cards()
    {
        suit = "unknown suit";
        number = 0;
    }

    public Cards(String suit, int number)
    {
        setSuit(suit);
        setNumber(number);

    }

    public void setCard(String suit, int number2)
    {
        setSuit(suit);
        setNumber(number2);

    }
    public void setSuit(String newSuit)
    {
        if(
            (newSuit.equalsIgnoreCase(HEARTS)) ||
            (newSuit.equalsIgnoreCase(DIAMONDS)) ||
            (newSuit.equalsIgnoreCase(CLUBS))    ||
            (newSuit.equalsIgnoreCase(SPADES)))
        {
            suit = newSuit;
        }
        else 
        {
            newSuit = "invalid";
            System.out.print("Invalid");
        }        
    }
    public int getNumber()
    {
        return number;
    }
    public String getSuit()
    {
        return suit;
    }

    public void setNumber(int newNumber)
    {

        if(newNumber >0 && newNumber <=10)
        {
            number = newNumber;
        }
        else
        {
            number = 0;
            System.out.print("invalid number");
        }
    }
}
도움이 되었습니까?

해결책

1) You need to override toString() in the Cards class. As is, you are printing out the reference of the object(the gibberish) instead of the "data." You should also override the toString() method of Deck to only print out the list.

2) I'm stepping through your code snippet of makeDeckFull(), and it seems to work fine. Are you sure those three inserts are where you are getting the invalid print statements?

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top