英文:
Why does declaring a new object give me a syntax error?
问题
我在高中,正在制作一个游戏。我尝试声明一个新对象:
public class Mapgen
{
public Checker map[]= new Checker[23];
map[0] = new Checker(red,2);
}
但是它给我两个错误提示:
"在此标记之后缺少“{”符号"
"语法错误,在此处插入“}”以完成 ClassBody"
我无法弄清楚问题出在哪里,感谢你的帮助。
英文:
I'm in highschool and I'm making a game. I tried to declare a new object:
public class Mapgen
{
public Checker map[]= new Checker[23];
map[0] = new Checker(red,2);
}
but it gave me 2 errors saying:
"Syntax error on token ";", { expected after this token"
"Syntax error, insert "}" to complete ClassBody"
I can't figure out what's the problem
thanks for your help
答案1
得分: 1
你在类级别上有一个赋值语句,这是不合法的。你需要将它放在一个方法内部,例如 main
方法:
public class Mapgen {
public static void main(String args[]) {
public Checker[] map = new Checker[23];
map[0] = new Checker(red,2);
}
}
请注意,与赋值不同,变量 map
的声明可以在类级别上 — 在这种情况下它是成员变量。在这种情况下,由于 main
是 static
的,你也需要将 map
声明为 static
,以便能够从 main
中访问它。
英文:
You have an assignment statement at class level, where it’s illegal. You need to put it inside a method, e.g. main
:
public class Mapgen {
public static void main(String args[]) {
public Checker[] map = new Checker[23];
map[0] = new Checker(red,2);
}
}
Note that, unlike the assignment, the variable declaration of map
can be at class level — in which case it’s a member variable. In that case, since main
is static
, you’d have to make map
static
, too, to be able to access it from main
.
答案2
得分: -1
你的代码没有包含在任何方法中,所以 "map[0] = new Checker(red,2);" 没有意义。
英文:
Your code is not within any method, so
map[0] = new Checker(red,2); makes no sense
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论