0

我已经为此搜索过,并且看到了一些类似的问题,但不是专门针对这个问题(无论如何我都能找到)。

我在这两个语句之前和之后的行中收到一个大括号/分号错误。它们是类的成员(不在类方法中)。当我删除数组分配行(第二行)时,大括号/分号错误消失了。我傻眼了,但知道有一个简单的答案。

public class Test {
    private int var1 = 1;

    // These are the troublesome lines
    public String[] name = new String[10];
    name[0] = "Mary"; // When I remove this line, both the errors go away

    public int var2 = 10;
}

我得到的 Eclipse (Juno) 中的错误是:

Syntax error on token ";", { expected after this token

...关于“var1”行上的错误,并且:

Syntax error, insert "}" to complete Block

...在“var2”行上。

我究竟做错了什么?我尝试了不同的差异,例如:

(String) name[0] = "Mary";

...等等。

4

3 回答 3

6

问题是这个语句:

name[0] = "Mary";

不在方法、构造函数或实例初始化程序中。只有声明(和初始化程序)可以位于类的顶层 - 而不是语句。

我建议你把它放在构造函数中。

public Test() {
    names[0] = "Mary";
}
于 2013-01-25T09:09:18.320 回答
4
public class Test {
    private int var1 = 1;


    // These are the troublesome lines
    public String[] name = new String[10];


    // Use a constructor for initialization or
    // declare the string array as   public String[] name = {"Mary" };
    public Test() {
       name[0] = "Mary"; // When I remove this line, both the errors go away
    }
    public int var2 = 10;
}

在java中,您必须将语句放入方法/块中。

例如

public class TestB {
    public String[] s = new String[10];


    {
        s[0] = "10";
    }

}

实际上是合法的(但我不会使用它,除了静态成员)

编辑:关于静态成员的说明

通常我们必须使用纯静态对象,在这种情况下,提供初始化的一种简单方法是使用匿名静态块。就像是:

public class TestStatic {
   private String [] someStaticStringArray = new String [10];
   static {
       someStaticStringArray[0] = "foo";
       someStaticStringArray[1] = "bar";
   }
   // Or better with static HashMaps
   private static HashMap<String, String> hm = new HashMap<String, String>();
   static {
     hm.put("key", "val");
     hm.put("key2", "val2");
     hm.put("key3", "val3");
   }
}

对于静态数据成员,当我没有办法提供工厂方法或工厂对象时,我就使用这种方式。对于非静态数据成员,我更喜欢使用构造函数,即使匿名块也有效。

在 java 中提供初始化的方法有很多,我想个人喜好是选择其中一种的主要原因。

对于您的特殊情况,我会选择这样的东西:

public class TestC {
   // Static data member, constructor does not read data from XML
   private static YourDataObject obj = new YourDataObject();

   public static YourDataObject getInstance(String xmlFile) {
      // Read XML file

      // Actually initialize the instance
      obj.set...(); // 

      // return the instance
      return obj;
   }
}
于 2013-01-25T09:10:13.567 回答
1

试试这个解决方案:

public String[] name = new String[10];

//  instance initializer code block comes
{
    name[0] = "Mary";
}

此代码块类似于静态初始化程序块 ( static { ... }),但在初始化变量时在实例化时执行。

于 2013-01-25T09:11:20.247 回答