gpt4 book ai didi

java - 无法在 switch 语句中使用枚举

转载 作者:行者123 更新时间:2023-12-01 17:24:01 25 4
gpt4 key购买 nike

我正在尝试在 switch case 中使用枚举。由于某种原因,switch case 在 netbeans 中声明它需要一个 int,但找到一个 enum。我将如何在 setStats() 中为我的 switch case 使用枚举?我正在使用 Java 7。

package rpgmanager;

import java.util.Random;

/**
*
* @author aaron
*/
public class CharacterClass {
Random random = new Random();
private int STR;
private int DEX;
private int CON;
private int WIS;
private int INT;
private int CHA;
private Enum SuperClass;

/**
*
*/
public CharacterClass(Enum Player_Class) {
SuperClass = Player_Class;
System.out.println("You are a handsome "+ Player_Class);
this.setStats();
}

/*
* Sets the users stats
*/
private void setStats() {
STR = random.nextInt(6) + 5;
DEX = random.nextInt(6) + 5;
CON = random.nextInt(6) + 5;
WIS = random.nextInt(6) + 5;
INT = random.nextInt(6) + 5;
CHA = random.nextInt(6) + 5;

switch (SuperClass) {
case Barbarian:
break;
default:
throw new AssertionError(SuperClass.name());
}
}

根据请求我的 ENUM 代码 -

    private enum Base_Class {
Barbarian, Bard, Cleric, Druid, Fighter, Monk,
Paladin, Ranger, Rogue, Sorcerer, Wizard
};

/*
* Sets the Base Class of the PC
*/
public void setBaseClass() {
do {
System.out.println("Available Classes: ");
System.out.println("Please select a cooresponding number for class.");
int i = 1;
for(Base_Class value: Base_Class.values()){
System.out.println(i+": "+value.name());
i++;
}
try {
System.out.print("Choice: ");
Base_Class_Choice = user_input.nextInt();
Player_Class = Base_Class.values()[Base_Class_Choice - 1];
try {
CharacterClass extendedClass = new CharacterClass(Player_Class);
extendedClass.getStatsList();
Extended_Class = extendedClass;
} catch (Exception e) {
System.out.println("Failed to build the character class!");
}
if (Base_Class_Choice < 1 || Base_Class_Choice > i) {
System.out.println("Not a valid number.");
}
} catch (Exception e) {
System.out.println("You must choose a valid class. Try numbers.");
user_input.next();
}
} while (Base_Class_Choice == 0);
}

最佳答案

您必须使用特定枚举类型,而不仅仅是Enum。例如,您可能有:

public enum PlayerClass {
WARRIOR,
BARBARIAN,
WIZARD;
}

public class GameCharacter {

private PlayerClass playerClass;

public GameCharacter(PlayerClass playerClass) {
this.playerClass = playerClass;
}

private void setStats() {
...
switch (playerClass) {
case BARBARIAN:
...
}
}
}

顺便说一句,我强烈建议您遵循 Java 命名约定 - 因此将变量命名为 strengthdexterity 等,而不是 STRDEX

关于java - 无法在 switch 语句中使用枚举,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16427671/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com