Gre*_*een 6 java arrays multidimensional-array
我不了解Java关于数组的行为.它禁止在一种情况下定义数组,但在另一种情况下允许相同的定义.
教程中的示例:
String[][] names = {
{"Mr. ", "Mrs. ", "Ms. "},
{"Smith", "Jones"}
};
System.out.println(names[0][0] + names[1][0]); // the output is "Mr. Smith";
Run Code Online (Sandbox Code Playgroud)
我的例子:
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;
}
}
Run Code Online (Sandbox Code Playgroud)
NetBeans引发的错误是:
非法开始表达,
";" 预期的,
不是声明.
而且它不承认的论点email,name,pass在定义users数组.但是当我定义u数组时识别它们.
这两个定义有什么区别?为什么一个工作但另一个定义相同的方式不?
das*_*ght 12
您需要new String[][]在数组聚合之前添加:
users = new String[][] { { email, name, pass }, {"one", "two", "three"} };
Run Code Online (Sandbox Code Playgroud)
您可以使用以下语法:
String[][] u = {{email, name, pass}, {"one@one.com", "jack sparrow", "12345"}};
Run Code Online (Sandbox Code Playgroud)
只有当你第一次声明矩阵时.在您在其他地方声明String[][]变量后,它将无法为变量赋值,这就是users = ...失败的原因.要将值分配给已声明的String[][](或任何其他类型的矩阵),请使用
users = new String[][] { { email, name, pass }, {"one", "two", "three"} };
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
13071 次 |
| 最近记录: |