我不明白Java关于数组的行为。它禁止在一种情况下定义数组,但允许在另一种情况下使用相同的定义。如何使用大括号在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}, {"[email protected]", "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的抛出的错误是:
表达的非法启动,
“ ;”预计,
不是一个声明。
并且它也不识别users阵列的定义中的参数email,name,pass。但是当我定义u数组时,它们会识别它们。
这两个定义有什么区别?为什么这个工作正常,但另一个定义的方式不一样?
2012-05-22
Green