我有三种不同的方法来声明Java中的字符串数组。其中一种始终有效,但另外两种只在按特定顺序编写时有效。
在第一个版本中,method2无法工作,但method3可以。
public class weirdStringArray {
String [] method1 = new String [] {"one","two","three"}; //<------ Works no matter where it's placed
String [] method2; //<------ "Syntax error on token ";", { expected after this token"
method2 = new String[3]; // Doesn't work in this postion
method2[0] = "one";
method2[1] = "two";
method2[2] = "three";
String [] method3 = new String[3]; //<------- No issue, works fine in this position
method3[0] = "one";
method3[1] = "two";
method3[2] = "three";
} // <----- Syntax error, insert "}" to complete ClassBody (but it does seem to complete ClassBody...?)
但是,如果交换位置,则工作声明也会交换。看,现在 method2 能用了,但是 method3 却不能用。
public class weirdStringArray {
String [] method1 = new String [] {"one","two","three"};
String [] method3 = new String[3]; //<------ "Syntax error on token ";", { expected after this token"
method3[0] = "one"; // Doesn't work in this postion
method3[1] = "two";
method3[2] = "three";
String [] method2; //<---------- Put it in a different place and it works
method2 = new String[3];
method2[0] = "one";
method2[1] = "two";
method2[2] = "three";
} // <----- Syntax error, insert "}" to complete ClassBody (but it does seem to complete ClassBody...?)
这里可能会发生什么?为什么顺序会有关系?第二个位置发生了什么?顺便提一下,如果我删除第一个有效的表单,也不会有任何影响。
public class weirdStringArray {
//String [] method1 = new String [] {"one","two","three"};
String [] method2; //<------ "Syntax error on token ";", { expected after this token"
method2 = new String[3]; // Doesn't work in this postion
method2[0] = "one";
method2[1] = "two";
method2[2] = "three";
String [] method3 = new String[3]; //<------- No issue, works fine in this position
method3[0] = "one";
method3[1] = "two";
method3[2] = "three";
} // <----- Syntax error, insert "}" to complete ClassBody (but it does seem to complete ClassBody...?)