我正在编写一个准系统游戏,我想用关键字轻松构建“怪物”,而不必每次都输入所有属性。
class Target {
public Target(String code) {
if (code.equals("biggest boss")) {
this.(code, 50);
} else if (code.equals("minion")) {
this.(code, 4);
}
}
public Target(String name, int health
/*various other attributes here */) {
this.name = name;
this.health = health;
}
String name;
int health;
}
但是,当然,当我运行它时,我收到错误对此的调用必须是构造函数中的第一个语句
。有什么建议么?谢谢!
最佳答案
没有“绕过它”的办法。假设您只有如图所示的两个条件,您可以这样做
this(code, "biggest boss".equals(code) ? 50 : 40);
或使用 Map<String, Integer>
和map.get(code)
解析该值 - 但 this
如果您想调用当前类中的另一个构造函数,则必须是第一行。
关于java - 如何绕过 "call to this must be first statement in constructor"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49686257/