2012-12-20 62 views
0

我學習Java,現在我似乎無法在此找出這些錯誤......問題與一些代碼

public class Input { 

    Setter access = new Setter(); 
//       ^Error here: Syntax error on token ";", { expected 
//        after this token. 

    if (commandExc == fly) { 
     access.flySetter(); 
    } 
    else if (commandExc == xray) { 
     access.xraySetter(); 
    } 
} // < Error here: Syntax error, insert "}" to complete ClassBody 

謝謝。

回答

3

代碼應該包裝在方法中,不應該直接在類體內。

3

你不能創建這樣的類。你的內部代碼必須在方法內。

像這樣:

public class Input { // start of class 

    public Input() { // start of constructor 
    Setter access = new Setter(); // this could be outside the method 

    // commandExc, fly and xray should be initialized somewhere 
    if (commandExc == fly) { 
     access.flySetter(); 
    } 
    else if (commandExc == xray) { 
     access.xraySetter(); 
    } 
    } // end of constructor 

} // end of class 

構造函數是特殊的,你把代碼初始化類的實例的方法。在這種情況下,我把代碼放在類的構造函數中。但它可以在任何其他方法內。你必須檢查你的程序更有意義。

當你正在學習Java,我建議你檢查這個環節,特別是「路線涵蓋基礎知識」: http://docs.oracle.com/javase/tutorial/

+0

哇,我完全忘了使用方法。我一直非常關注代碼語法和whatnot。謝謝。 – Jordanss10

+0

很高興我能幫忙:)。我已經爲java教程添加了一個鏈接。這是學習Java的好地方。 – ceklock

1
public class Input { 

    Setter access = new Setter(); 

    public static void main(String args[]) { //or any method 
     if (commandExc == fly) { 
      access.flySetter(); 
     } 
     else if (commandExc == xray) { 
      access.xraySetter(); 
     } 
    } 
} 
0

看起來你不是一個方法裏面工作。嘗試將代碼放入的main方法中。例如:

public class Input { 
    public static void main(String[] args) { 
    Setter access = new Setter(); 

    if (commandExc == fly) { 
     access.flySetter(); 
    } 
    else if (commandExc == xray) { 
     access.xraySetter(); 
    } 
    } 
} 

如果這本來是一個對象,的access初始化部分放入一個構造函數方法。 if/else的位置取決於所需的實現。

0

您應該將代碼包裝在方法中。就像下面這樣:

public class Input { 

    Setter access = new Setter(); 

    public static void main(String args[]){ //or any method 
     if (commandExc == fly) { 
      access.flySetter(); 
     } 
     else if (commandExc == xray) { 
      access.xraySetter(); 
     } 
    } 

}