我收到语法错误“insert } to complete ClassBody。
这段代码工作正常/没有错误:
import java.awt.Rectangle;
class Trigger
{
Type type;
long time;
ObjectID controlType;
int controlNum;
int resType, resNum;
Rectangle location;
enum Type {TIMED, CONTROLED, LOCATION, RESOURCE};
Trigger()
{
}
}
但是,当我像这样添加构造函数时,出现错误:
class Trigger
{
Type type;
long time;
ObjectID controlType;
int controlNum;
int resType, resNum;
Rectangle location;
enum Type {TIMED, CONTROLED, LOCATION, RESOURCE}; //I get the error on this line
Trigger(Type.TIMED, long t)
{
time = t;
}
Trigger(Type.CONTROLLED, int c)
{
controlNum= c;
}
Trigger(Type.LOCATION, int locx, int locy, int w, int h)
{
location = new Rectangle(locx, locy, w, h);
}
Trigger(Type.RESOURCE, int resT, int resN)
{
resType = resT;
resNum = resN;
}
}
**请注意,我是在处理中编写这段代码!
如果我将枚举行移动到顶部(在“Type type;”上方),则错误消息会跳转到“Rectangle location;”行
那么这里发生了什么?我不明白为什么我没有收到第一个代码的错误,但我收到了第二个代码的错误!
更新
好的,我更改了代码,使枚举在每个构造函数中初始化类型变量。这将是我正在帮助设计一个类(class)项目的 rts。还有另一个名为 GameEvent 的类,其中有一个触发器实例和一个 Action 数组列表。触发器将从文件上传,然后 Action 将被硬编码(我知道这种风格不好,但只有 3 个任务,助教说我们不会因此而丢分)。所以 child 类听起来是个好主意。但为什么它不能正常工作?
这是更新后的代码:
import java.awt.Rectangle;
class Trigger
{
Type type;
long time;
FCObjectID controlType;
int controlNum;
int resType, resNum;
Rectangle location;
enum Type {TIMED, CONTROLED, LOCATION, RESOURCE};
Trigger(Type.TIMED, long t)
{
type = TIMED;
time = t;
}
Trigger(Type.CONTROLLED, int c)
{
type = CONTROLED;
controlNum= c;
}
Trigger(Type.LOCATION, int locx, int locy, int w, int h)
{
type = LOCATION;
location = new Rectangle(locx, locy, w, h);
}
Trigger(Type.RESOURCE, int resT, int resN)
{
type = RESOURCE;
resType = resT;
resNum = resN;
}
}
最佳答案
您的构造函数不正确。例如:
Trigger(Type.LOCATION, int locx, int locy, int w, int h)
您希望参数列表中的 Type.LOCATION 部分做什么?每个参数都应该是一个类型,后跟参数名称(如 int locx
等正确)。
您是否尝试根据调用者是否尝试指定位置、时间等来添加不同的构造函数?如果是这样,那绝对不是您的做法……但听起来您可能无论如何都希望为每种情况使用单独的类。
关于java - 添加构造函数会出错?这没有意义请帮助,编程问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5134529/