Why am I receiving errors on Java array assignment? [duplicate]

故事扮演 提交于 2021-02-17 05:53:05

问题


I am trying to assign int literals to certian indexs of the array. I keep getting errors from the compiler. This article seems to suggest That I have done this correctly. Here is the code:

public class Mytest {
    int[] jim = new int[9];
    jim[0] = 77;
}

Compiler Errors:

Mytest.java:5: error: ']' expected
    jim[0] = 77;
        ^
Mytest.java:5: error: ';' expected
    jim[0] = 77;
         ^
Mytest.java:5: error: illegal start of type
    jim[0] = 77;
           ^
Mytest.java:5: error: <identifier> expected
    jim[0] = 77;
            ^

Thanks in advance.


回答1:


You need to move your assignment statement to a valid location. This could be a method, a constructor, or an initialization block.

public class Mytest {
    int[] jim = new int[9];
    // Using an initialization block
    {
        jim[0] = 77;
    }
}



回答2:


You have to put them into a method or into a constructor, which is a 'special' method.

You have to put those lines inside your main method, if 'Mytest' is your main class, or in any other method you create for that, inside that class.



来源:https://stackoverflow.com/questions/28594656/why-am-i-receiving-errors-on-java-array-assignment

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!