2014-12-21 27 views
2

我在我的课程上创建了一个静态字段c,但它产生了一个错误,说illegal start of expression创建静态字段时出错

请帮我解决这个问题。

public static void main(String[] args) { 

    System.out.println("program started.");  
    static Controller c; //Where the error is 

    try { 
     Model m = new Model(); 
     View v = new View(); 
     c = new Controller(m,v); 
     c.sendDataToView(); 
     c.showView(); 
    } catch(Exception ex) { 
     System.out.println("error"); 
    } 
} 

回答

2

你不能在方法内部声明static场(或任何其他领域,对于这个问题),即使它是一个static一个。

您可以申报法外static场:

static Controller c; 
public static void main(String[] args) { 
    System.out.println("program started."); 

    try { 
     Model m = new Model(); 
     View v = new View(); 
     c = new Controller(m,v); 
     c.sendDataToView(); 
     c.showView(); 
    }catch(Exception ex) { 
     System.out.println("error"); 
    } 
} 

或纯老式的局部变量:

public static void main(String[] args) { 
    System.out.println("program started."); 

    Controller c; 
    try { 
     Model m = new Model(); 
     View v = new View(); 
     c = new Controller(m,v); 
     c.sendDataToView(); 
     c.showView(); 
    }catch(Exception ex) { 
     System.out.println("error"); 
    } 
} 
+0

能否请您解释一下我为什么声明一个领域内的方法是不允许? – Francisco

+0

@Francisco这不仅仅是java的工作方式 - 字段是**类**的成员,所以他们应该在类下声明 - 方法内的变量对于该方法是本地的,因此不需要(并且可以没有)访问修饰符,除了'final'。 – Mureinik

1

你不能在方法中声明静态字段。

外移它:

static Controller c; 

public static void main(String[] args) 
{ 
    System.out.println("program started."); 
    try { 
     Model m = new Model(); 
     View v = new View(); 
     c = new Controller(m,v); 
     c.sendDataToView(); 
     c.showView(); 
    } catch(Exception ex) { 
     System.out.println("error"); 
    } 
}