问题
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