【发布时间】:2015-03-23 20:23:10
【问题描述】:
我正在尝试使用 values 方法来查找枚举类型的给定值。出于某种原因,它说我必须创建一个 values() 方法,但这应该是一个内置方法(至少我是这么认为的)。这是我遇到问题的代码:
public class Suit {
public enum SUIT{
CLUBS("Clubs"), HEARTS("Hearts"), SPADES("Spades"), DIAMONDS("Diamonds");
private String suitType;
SUIT(String suitType){
this.suitType = suitType;
}
public String getSuit(){
return suitType;
}
}
}
public class Rank {
private static int ACEVal;
public void setACEVal(int ACEVal){
this.ACEVal = ACEVal;
}
public int getACEVal(){
return ACEVal;
}
public enum RANK{
ACE(14, "Ace"),
TWO(2, "Two"),
THREE(3, "Three"),
FOUR(4, "Four"),
FIVE(5, "Five"),
SIX(6, "Six"),
SEVEN(7, "Seven"),
EIGHT(8, "Eight"),
NINE(9, "Nine"),
TEN(10, "Ten"),
JACK(10, "Jack"),
QUEEN(10, "Queen"),
KING(10, "King");
public int rankVal;
String cardType;
RANK(int rankValue, String cardType){
rankVal = rankValue;
this.cardType = cardType;
}
public int getRankVal(){
return rankVal;
}
public String getCardType(){
return cardType;
}
}
}
public class CreateDeck {
ArrayList<CreateCard> DeckArray = new ArrayList<CreateCard>(); //uses the cards that were created in CreateCard to load into the ArrayList
public void createDeck(){
for(int i = 0; i < 13; i++){ //loops thirteen times for each different type of card (Ace, Two, Three, etc...){
Rank rankNum = Rank.values()[i]; //gets the type of rank
for(int j = 0; j < 4; j++){ //loops for the four different suits (Clubs, Spades, Hearts, Diamonds)
CreateCard card = new CreateCard(rankNum, Suit.values()[j]);
DeckArray.add(card); //adds the created card to the deck
}
}
为什么我无法使用 .values()?
【问题讨论】:
-
您还需要发布“西装”的代码。
-
请编辑您的问题以包含 Rank 类的代码。
-
那么,Rank 是一个枚举吗?
-
考虑将您的 for 循环与索引更改为
for (Rank rank : Rank.values()) ...,这更容易。 -
你的枚举是 Suit.SUITS 和 RANK。然而,您正在调用 Suit.values 和 Rank.values。请注意,SUITS 嵌入在 Suit 中。 RANK 没有嵌入到 Rank 中。无论如何 values() 不存在,因为您在错误的类型上调用它。仔细观察你的名字。
标签: java methods arraylist enums