类中的Java字符串数组 - Eclipse中的卷曲大括号错误

问题描述 投票:0回答:3

我已经搜索过这个问题,并且已经看到了一些类似的问题,但没有特别提出这个问题(无论如何我都能找到)。

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

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";

...等等。

java arrays string curly-braces
3个回答
6
投票

问题是这句话:

name[0] = "Mary";

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

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

public Test() {
    names[0] = "Mary";
}

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;
   }
}

1
投票

尝试此解决方案:

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

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

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

© www.soinside.com 2019 - 2024. All rights reserved.