关闭括号/分号的错误

时间:2011-11-02 17:51:21

标签: java debugging

我的一个课程中有两个编译错误,我不明白他们为什么会在那里。

最大的错误是说需要另外一个分号,而最后一个则说它需要另一个结束括号。

如果我放入另一个大括号但是顶部的大括号没有,则底部错误消失。有什么想法吗?

(这可能是我失明/愚蠢的情况,所以我提前道歉:)

package com.pathfinding;

import java.util.ArrayList;


public class EdgeNodeFactory
{
static boolean[][] edgeMatrix = new boolean[100][100];
for (int i = 0; i < 100; i++)
{
    for (int j = 0; j < 100; j++)
    {
        edgeMatrix[i][j] = false;
    }
}

static ArrayList<Node> nodes = new ArrayList<Node>();
static ArrayList<Edge> edges = new ArrayList<Edge>();

static int edgeCount = 0;
static int nodeCount = -1;
}

errors regarding curly braces

3 个答案:

答案 0 :(得分:2)

您已尝试将代码(for循环)直接放在您的类中 - 它不在构造函数,方法或静态/实例初始化程序中。那是无效的。您希望何时执行该代码?

怀疑你的代码看起来应该是这样的:

public class EdgeNodeFactory
{
    private boolean[][] edgeMatrix = new boolean[100][100];
    private int edgeCount = 0;
    private int nodeCount = -1;
    private List<Node> nodes = new ArrayList<Node>();
    private List<Node> edges = new ArrayList<Edge>();

    public EdgeNodeFactory()
    {
        // You *could* put your for loop here... but the array
        // elements will all be false anyway, as that's the default...

        // If you don't need any code in this constructor, and you
        // don't declare any other constructors, you can remove it
        // entirely - the compiler will create it by default.
    }

    // Other methods here
}

请注意我是如何将所有字段设为私有和非静态的...您几乎肯定会创建EdgeNodeFactory实例而不是使用静态字段,并且你应该几乎总是将字段设为私有。

答案 1 :(得分:2)

我做过任何Java已经有一段时间了,但我相信for循环应该在某个描述的方法或函数中,而不是类声明。

我想你的意思是在构造函数中。

答案 2 :(得分:0)

我认为for循环的意思是静态数组字段的初始化。在这种情况下,您应该将代码放在静态初始化程序中,如下所示:

package com.pathfinding;

import java.util.ArrayList;


public class EdgeNodeFactory
{
static boolean[][] edgeMatrix = new boolean[100][100];
static {
  for (int i = 0; i < 100; i++)
  {
      for (int j = 0; j < 100; j++)
      {
          edgeMatrix[i][j] = false;
      }
  }
}

static ArrayList<Node> nodes = new ArrayList<Node>();
static ArrayList<Edge> edges = new ArrayList<Edge>();

static int edgeCount = 0;
static int nodeCount = -1;
}

类级别static { ... }内的代码在第一次加载类时执行(仅一次)。这意味着它将在创建类的任何实例之前以及任何其他代码可以访问该类之前执行。

字段是否应该是静态的仍然存在争议,但如果你确定它们应该是,那么这就是你应该如何初始化它们。

相关问题