更正了Java错误但无法解释为什么错误 [英] Corrected a Java error but unable to get why it was wrong

查看:68
本文介绍了更正了Java错误但无法解释为什么错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个java类代码 -

I had this java class code -

public class game_setter {

    private String[] blocks = new String[3];

    blocks[0] = "a";
    blocks[1] = "b";
    blocks[2] = "c";

}



错误突出显示是 - 令牌上的语法错误;,{此符号之后的预期





所以我试着纠正代码。

没有错误的新代码是 -


And the error highlighting was - Syntax error on token ";", { expected after this token


So I tried to correct the code.
The new code with no error is -

public class game_setter {

    private String[] blocks = new String[3];

    {
    blocks[0] = "a";
    blocks[1] = "b";
    blocks[2] = "c";
    }

}





但是我无法理解为什么错误存在且如何通过添加括号来纠正它?



But I'm unable to understand why the error was there and how it got corrected by just adding brackets?

推荐答案

您的变量 blocks 作为类成员被解除。



之后你尝试为成员分配值 - 这在课堂体内是不允许的,只在方法中。





这是处理这个问题的正确方法:



Your variable blocks is decleared as a class member.

After that you try to assign values to the member - that is not allowed in class body, only in method.


This is the correct way to handle that:

public class game_setter { // class ALWAYS starts with capital letter! No underscores please!
 
    private String[] blocks = new String[3];
 

    public game_setter() {
        blocks[0] = "a";
        blocks[1] = "b";
        blocks[2] = "c";
    }
 
}


这篇关于更正了Java错误但无法解释为什么错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆