2017-06-02 50 views
-1

我剛開始學習java,並不熟悉這門語言。這是一個在線任務,我爲了獲得樂趣並獲得更多的熟悉,並且無法弄清我在構造函數行中遇到的多個錯誤。請幫助此行有多個標記,Java構造函數錯誤(初學者級別)。

public class WhackAMole { 
    public static void main(String[] args) { 
    int score; 
    int molesLeft; 
    int attemptsLeft; 
    char [][]moleGrid=new char[10][10]; 
    int numAttempts; //is this needed 
    int gridDimensions; // is this also needed 

    /*Multiple markers at this line 
- Syntax error on token "int", delete this token 
- Syntax error, insert ";" to complete Statement 
- Syntax error on token "int", delete this token 
- numAttempts cannot be resolved to a variable 
- gridDimensions cannot be resolved to a variable 
- Syntax error on token "int", delete this token 
- The method WhackAMole(int, int) is undefined for the type 
WhackAMole*/ 
    WhackAMole(int numAttempts, int gridDimensions) { 
     this.numAttempts=numAttempts ; //error-cannot use this in static content 
     this.gridDimensions=gridDimensions ; // error-cannot use this in static content 

} 

} 

} 
+0

你不關閉你的主要方法。在'int gridDimensions'之後;'添加一個'}'並從下面刪除1'}'。 –

+0

您必須將構造函數和字段移出'main' – QBrute

+0

您是混合方法和構造函數。 –

回答

3

將您的構造函數移出main()方法。

+0

不只是構造函數。他也需要移動屬性。他使用構造函數中的變量 – Dennux

2

我建議你做一些基本的初學者級別的java教程。你不能把構造函數放在另一個方法中(它在主要方法中)。還要使用this.numAttempts你需要對象屬性。我試圖移動代碼片段以使其更具有意義:

public class WhackAMole { 

    // Those are attributes 
    private int score; 
    private int molesLeft; 
    private int attemptsLeft; 
    private char[][] moleGrid = new char[10][10]; 
    private int numAttempts; // is this needed 
    private int gridDimensions; // is this also needed 

    // Constructor 
    public WhackAMole(int numAttempts, int gridDimensions) { 
     this.numAttempts = numAttempts; 
     this.gridDimensions = gridDimensions; 
    } 

    public void play() { 
     // Game logic here 
    } 

    /* This Method should propably be in another class */ 
    public static void main(String[] args) { 

     final WhackAMole wham = new WhackAMole(42, 1234567); 
     wham.play(); 
    } 
} 
+0

謝謝,這個任務只是來自開發級別的類...將繼續嘗試 – LightPalace

1

您在java中不允許的方法中定義了方法。此外,我已將屬性移至課程級別。

請使用如下代碼:

public class WhackAMole { 

    int score; 
    int molesLeft; 
    int attemptsLeft; 
    char[][] moleGrid = new char[10][10]; 
    int numAttempts; //is this needed 
    int gridDimensions; // is this also needed 

    WhackAMole(final int numAttempts, final int gridDimensions) { 
     this.numAttempts = numAttempts; //error-cannot use this in static content 
     this.gridDimensions = gridDimensions; // error-cannot use this in static content 
    } 

    public static void main(final String[] args) { 
     WhackAMole whackAMole = new WhackAMole(30, 40); 
     System.out.println("numAttempts:" + whackAMole.numAttempts + " gridDimensions:" + whackAMole.gridDimensions); 
    } 
} 
+0

我注意到你在構造函數中使用了最後的int,它與int不同麼? – LightPalace

+0

請閱讀java的基礎知識來理解final關鍵字。 –