2016-05-24 4 views
0
public enum Difficulty { 
EASY, //easy game, lots of villages to spare 
NORMAL, //normal game, fewer villagers & bullets 
HARD; //hard game, the wolf relocates when shot 

/** 
* Returns a multi-line String describing the characteristics of this 
* difficulty level. 
*/ 
public String toString() { 
    return "Player starts in the village: " + getPlayerStartsInVillage() + 
      "\nNumber of villagers: " + getVillagerCount() + 
      "\nAvailable silver bullets: " + getSilverBulletCount() + 
      "\nWerewolf moves when shot: " + getWolfMovesWhenShot(); 
} 

/** 
* Returns true if the player starts in the same area as the village for 
* this difficulty level, false otherwise. 
*/ 
public boolean getPlayerStartsInVillage() { 
    return this == EASY; 
} 

/** 
* Returns the initial number of villagers for this difficulty level. 
*/ 
public int getVillagerCount() { 
    switch (this) { 
    case EASY: return 6; 
    case NORMAL: return 4; 
    default /*HARD*/: return 4; 
    } 
} 

/** 
* Returns the number of silver bullets the player starts with in this 
* difficulty level. 
*/ 
public int getSilverBulletCount() { 
    switch (this) { 
    case EASY: return 8; 
    case NORMAL: return 6; 
    default /*HARD*/: return 6; 
    } 
} 

/** 
* Returns true if the werewolf moves when hit, false otherwise. 
*/ 
public boolean getWolfMovesWhenShot() { 
    return this == HARD; 
} 

私はこのメソッドを使用するために呼びたい(上の)クラスを持っていますが、わかりません。私は知っているJava enumをインスタンス化する方法

Difficulty obj1 = new Difficulty(); 

しかし、それは '困難をインスタンス化できません'と返されます。誰かがこのコードを書くためにどのようなコードを書くか教えてもらえますか?

Difficulty obj1 = new Difficulty(); 

をそして、そのための十分な理由があります:

​​
+1

を読むために

Difficulty obj1 = Difficulty.NORMAL 

良いあなたは '難しOBJ1 = Difficulty.EASY'を試みたことがありますか? – Arc676

+1

さらに、この方法では 'switch'を使用しないでください。代わりに 'final'フィールドを列挙型に追加し、コンストラクタを使用してそれらを初期化します。ここのplanetsの例を参照してください。https://docs.oracle.com/javase/tutorial/java/javaOO/enum.html – fabian

答えて

0

あなたは列挙型をこのようにインスタンス化することはできません。

関連する定数の固定セットがある場合の列挙型です。 1つをインスタンス化したくないのは、セットが固定されないためです。

何がやりたいことは、このようなものです:Oracle Tutorial Java Enums

関連する問題