Preeyah Preeyah - 2 months ago 8
Java Question

JAVA - Error incompatible types: String cannot be converted to String[ ]

I'm working on Java project - Playing Cards.

And, in this Card.java class, I've declared and initialized variables and array list. I've come across this error. These errors are under each getter and setter methods.

error: incompatible types: String cannot be converted to String[]
error: incompatible types: int[] cannot be converted to int

public class Card {

// private String suit;
//private String name;
//private int value;

private String[] suit = {"spades","hearts","clubs","diamonds"};
private String[] name = {"Ace","Jack","Queen","King"};
private int[] value = {1,2,3,4,5,6,7,8,9,10,11,12,13};

public Card(String s, String n, int v)
{
suit = s;
name = n;
value = v;
}

public String getSuit()
{
return suit;
}

public String getName()
{
return name;
}

public int getValue()
{
return value;
}

public String toString()
{
return "<"+suit+" "+name+">";
}


This is the whole class.

Hope anyone knows and can help me out, thanks! (:

If you don't understand what i'm trying to get at, let me know, try my best to explain

R.J R.J
Answer

I bet you generated the getters and setters and the constructor for the initial set of fields which are these.

// private String suit;
// private String name;
// private int value;

But after changing them to

private String[] suit = { "spades", "hearts", "clubs", "diamonds" };
private String[] name = { "Ace", "Jack", "Queen", "King" };
private int[] value = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13 };

you forgot to modify them accordingly. You need to change your getters and setters and constructors to something like this. The same goes with the toString() method.

public class Card {

    private String[] suit = { "spades", "hearts", "clubs", "diamonds" };
    private String[] name = { "Ace", "Jack", "Queen", "King" };
    private int[] value = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13 };

    public Card(String[] suit, String[] name, int[] value) {
        super();
        this.suit = suit;
        this.name = name;
        this.value = value;
    }

    public String[] getSuit() {
        return suit;
    }

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

    public String[] getName() {
        return name;
    }

    public void setName(String[] name) {
        this.name = name;
    }

    public int[] getValue() {
        return value;
    }

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

    @Override
    public String toString() {
        return "Card [suit=" + Arrays.toString(suit) + ", name="
            + Arrays.toString(name) + ", value=" + Arrays.toString(value)
            + "]";
    }
}

Always remember to generate fresh getters, setters, constructor, toString() methods, if you happen to change the fields in the class.