有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

如何实例化Java枚举

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

我有一个(上面的)类,我想在下面调用它来使用它的方法,但我不确定如何使用。我知道

Difficulty obj1 = new Difficulty(); 

但这会带来“无法实例化困难”。有人能告诉我要写什么代码才能让它工作吗

public class WereWolfenstein2D {
}

共 (1) 个答案

  1. # 1 楼答案

    不能以这种方式实例化枚举:

    Difficulty obj1 = new Difficulty();
    

    这是有充分理由的

    枚举适用于具有固定的相关常量集的情况。您不想实例化一个,因为这样集合就不会被修复

    你想做的事情是这样的:

    Difficulty obj1 = Difficulty.NORMAL
    

    好读Oracle Tutorial Java Enums