2011-11-02 56 views
0

我在其中一个类中有两个编译错误,我不明白他们为什么在那里。右花括号/分号错误

最高的错误是说需要另一个分号,最下面的一个说它需要另一个右大括号。

如果我放入另一个大括号,但最上面一个没有,底部错误消失。有任何想法吗?

(这大概是我失明的情况下/愚蠢的,所以我提前:)

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

+0

请更新文章出处:密码: –

+0

将文件粘贴到此页? –

+0

而不是屏幕抓取,请张贴实际的代码。 – Oded

回答

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而不是使用静态字段,你应该几乎总是使字段私有。

+0

哦,谢谢!这真的会清理我的代码! – bananamana

2

自从我做了任何Java以来​​已经有一段时间了,但我认为for循环应该在某个描述的方法或函数内部,而不是类声明。

我会想象你的意思是在一个构造函数。

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 { ... }在类级别执行首次类被加载(仅一次)。这意味着它将在类的任何实例创建之前以及任何其他代码可以访问该类之前执行。

这些字段是否应该是静态的,但如果你确定他们应该这样,这是你应该如何初始化它们的问题。