2013-09-29 50 views
1

我是編程新手,如果看起來很可怕,請原諒我。我不太確定我在做什麼。錯誤:構造函數類卡中的卡片不能應用於給定的類型;

當我編譯代碼我得到以下錯誤:

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------------ 
} 

回答

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

你正試圖在這裏建立一個卡:

使用不存在構造函數。

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); 
+0

我將如何創建一個構造? – user2827773

+0

@ user2827773看看我編輯請 –

1

添加到您的類:

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