Home > Back-end >  How can I use a method Get, of another class to print this array?
How can I use a method Get, of another class to print this array?

Time:06-24

I'm trying to print my array deck, when I use this printf,

gives a message like: "jamilzin.cassino.Deck@28a418fc"

However when I tried to create a method philippines in my Deck Class,

my printf return message like: "jamilzin.cassino.Card@63a418fc"

How can I use a correct casting to use my getValue and getSuit to print my array?

My idea: create a object Deck(), as Deck is a Array of Card, i want cast something like a MyDeck(Card.getValue), but idk how to do it

    package jamilzin.cassino;
    
    import java.util.ArrayList;
    import java.util.Arrays;
    import java.util.Random;
    
    Deck class: 
    
    public class Deck {
    
        private Card[] deck;
        private String[] suits = {"Ouro", "Paus", "Espada", "Copas"};
        private Random gerador = new Random();
        
        public Deck(){
            deck = new Card[52];
            int k = 0;
            for(int j = 0; j< suits.length;j  ){
                for(int i = 0;i< 13;i  ){
                    deck[k] = new Card((i 1),suits[j]); 
                    k  ;
                }
            }
        }}

--------------------------------
Card class:
package jamilzin.cassino;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Random;

public class Card {
    
    private String suit;
    private int value;
    
    Card(int value, String suit){
    this.value = 0;
    this.suit = " ";
    
    }

    public String getSuit() {
        return suit;
    }

    public void setSuit(String suit) {
        this.suit = suit;
    }

    public int getValue() {
        return value;
    }

    public void setValue(int value) {
        this.value = value;
    }

    ----------------------------------

Test class:

public class Cassino {
 
    public static void main(String[] args) {
        
 Deck deckMaster = new Deck();
 System.out.println(""  deckMaster);
       
        }}

CodePudding user response:

Your solution is close. When you call System.out.println("" deckMaster), the Deck doesn't define how it should print itself. You can fix that by adding something like this to the Deck class:

@Override
public String toString() {
    return Arrays.toString(deck);
}

From there, it will print each Card, but they also don't know how to print themselves, so you could try adding something like this to the Card class:

@Override
public String toString() {
    return getValue()   getSuit();
}

Also, your constructor for Card is ignoring all input parameters, which is probably not what you want. So change this:

Card(int value, String suit) {
    this.value = 0;
    this.suit = " ";
}

to this:

Card(int value, String suit) {
    this.value = value;
    this.suit = suit;
}
  • Related