我不了解 Java 关于数组的行为。它禁止在一种情况下定义数组,但在另一种情况下允许相同的定义。
教程中的示例:
String[][] names = {
{"Mr. ", "Mrs. ", "Ms. "},
{"Smith", "Jones"}
};
System.out.println(names[0][0] + names[1][0]); // the output is "Mr. Smith";
我的例子:
public class User {
private static String[][] users;
private static int UC = 0;
public void addUser (String email, String name, String pass) {
int i = 0;
// Here, when I define an array this way, it has no errors in NetBeans
String[][] u = { {email, name, pass}, {"one@one.com", "jack sparrow", "12345"} };
// But when I try to define like this, using static variable users declared above, NetBeans throws errors
if (users == null) {
users = { { email, name, pass }, {"one", "two", "three"} }; // NetBeans even doesn't recognize arguments 'email', 'name', 'pass' here. Why?
// only this way works
users = new String[3][3];
users[i][i] = email;
users[i][i+1] = name;
users[i][i+2] = pass;
UC = UC + 1;
}
}
NetBeans 抛出的错误是:
非法的表达开始,
“;” 预计,
不是声明。
而且它也不识别数组定义中的参数email
, 。但是当我定义数组时识别它们。name
pass
users
u
这两个定义有什么区别?为什么一个有效,而另一个以相同方式定义的无效?