6

我不了解 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, 。但是当我定义数组时识别它们。namepassusersu

这两个定义有什么区别?为什么一个有效,而另一个以相同方式定义的无效?

4

4 回答 4

12

您需要new String[][]在数组聚合之前添加:

users = new String[][] { { email, name, pass }, {"one", "two", "three"} };
于 2012-05-22T18:13:00.017 回答
5

您可以使用以下语法:

String[][] u = {{email, name, pass}, {"one@one.com", "jack sparrow", "12345"}};

当您第一次声明矩阵时。在您在别处声明String[][]变量,它无法为变量赋值,这就是users = ...失败的原因。要将值分配给已声明的String[][](或任何其他类型的矩阵),请使用

users = new String[][] { { email, name, pass }, {"one", "two", "three"} };
于 2012-05-22T18:14:29.433 回答
2

第一种情况是初始化语句,而第二种情况只是赋值。只有在定义新数组时才支持这种填充数组。

于 2012-05-22T18:14:03.970 回答
2

要重新分配矩阵,您必须使用new

users = new String[][] {{email, name, pass }, {"one", "two", "three"}};
于 2012-05-22T18:16:55.640 回答