错误:类卡中的构造函数卡不能应用于给定类型;

时间:2013-09-29 06:09:29

标签: java

我是编程的新手,请原谅我,如果它看起来很可怕。我不太确定我在做什么。

编译代码时出现以下错误:

error: constructor Card in class Card cannot be applied to given types;
required: no arguments
found: String, String, int
reason: actual and formal arguments differ in length

这是我的代码:

public void testConvenienceConstructor() {
    System.out.println("Card...");
    Card instance = new Card("4", DIAMONDS, 4);
    assertEquals("4", instance.getName());
    assertEquals(DIAMONDS, instance.getSuit());
    assertEquals(4, instance.getValue());

这是我的卡类代码:

package model;

public class Card implements CribbageConstants {
//-----fields-----
private String name;     //the name of the card
private String suit;     //the suit of the card
private int value;       //the value of the card

//---------- Constructors ---------
/**
 * No argument constructor - set default values for card
 */
public Card() {

        name = "ACE";
        suit = "CLUBS";
        value = 1;
    }
//-------------- Utility methods --------------

    /**
     * Provide a text representation of a card.
     *
 * @return The banana's name, suit, and value
 */
public String getName() {
    return name;
}

public String getSuit() {
    return suit;
}

public int getValue() {
    return value;
}

//------mutator-----
public void setName(String name) {
    this.name = name;
}

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

public void setValue(int value) {
    this.value = value;
}
//-----------utility methods------------
}

3 个答案:

答案 0 :(得分:1)

使用new Card("4", DIAMONDS, 4);,您正在调用Card的构造函数,该构造函数需要StringStringint。但是没有这样的构造函数存在!所以这就是编译器不高兴的原因。

将此添加到您的代码中:

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

答案 1 :(得分:1)

你正在尝试在这里建造一张卡片:

Card instance = new Card("4", DIAMONDS, 4);

使用不存在的构造函数。

在类Card中,您需要创建一个接受给定类型的构造函数:

public Card(String nme, String suit, int val) {

        name = nme;
        suit = suit;
        value = val;
}

您还必须发送DIAMONDS作为我认为的字符串(用双引号括起来):

Card instance = new Card("4", "DIAMONDS", 4);

如果您不想添加其他构造函数,可以更改启动代码:

Card instance = new Card();
instance.setName("4");
instance.setSuit("DIAMONDS");
instance.setValue(4);

答案 2 :(得分:1)

将此添加到您的班级:

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