2013-09-29 68 views
0

我更新的編程,並繼續獲取非靜態方法不能從靜態上下文從我的螞蟻類調用我的地板類時引用。我刪除了所有的靜態信息,並且仍然出現這個錯誤,如果有人能指出我的方向是正確的,還是讓我知道這個問題會很好,謝謝。非靜態方法不能從靜態上下文中引用(Java)

public class Ant { 

    public final int RED = 0, BLUE = 1, NORTH = 0, 
      EAST = 1, SOUTH = 2, WEST = 3; 
    public int color; 

    public Ant(int size, int dir) { 
     size = size; 
     dir = startDir; 
     floor floor = new floor(size); 
    } 

    public int getRow() { 
     return row; 
    } 

    public int getCol() { 
     return col; 
    } 

    public void makeMoves(int numMoves, int dir) { 
     final int[][] offSet = {/* NORTH */ {-1, 0}, 
           /* EAST */ {0, 1}, 
           /* SOUTH */ {1, 0}, 
           /* WEST */ {0,-1}}; 

     final int[][] newDir = {/* NORTH */ {WEST, EAST}, 
           /* EAST */ {NORTH, SOUTH}, 
           /* SOUTH */ {EAST, WEST}, 
           /* WEST */ {SOUTH, NORTH}}; 
     //set start row, col, and direction 
     row = col = size/2; 

     for(int move = 1; move <= numMoves; move ++) { 
      //make a move based on direction 
      row = row + offSet[dir][0]; 
      col = col + offSet[dir][1]; 

      //turn based on color of new tile and direction 
      color = floor.getTileColor(row, col); 
      dir = newDir[dir][color]; 

      //change color of current tile 
      floor.changeTileColor(row, col); 
     }  
    }//End of makeMoves 
}//End Ant class 

public class floor {  
    int [][] grid; 

    public floor(int size) { 
     grid = new int[size][size]; 
    } 

    public int getTileColor(int row, int col) { 
     return grid[row][col]; 
    } 

    public void changeTileColor(int row, int col) { 
     int color = grid[row][col]; 
    } 
} 
+2

哪一行給出錯誤? – ssantos

+0

請顯示導致錯誤的代碼行。 –

+0

@hexafraction:這對我來說似乎不是這樣。他似乎在問,因爲他不認爲他有任何靜態代碼,並不是因爲他想知道他爲什麼不能從靜態代碼中調用非靜態代碼。 – Dolda2000

回答

1

由於其他原因,該代碼無法編譯。例如,在這個構造函數中,startDir沒有被定義。雖然規模已經確定,但這並沒有做任何事情。它將參數大小分配給它自己。你真的想要this.size = size;

public Ant(int size, int dir) 
    { 
     size = size; 
     dir = startDir; 

此外,行和列沒有在任何地方定義。如果您遇到關於靜態的錯誤,我想知道您是否正在編譯舊代碼。

1

public static void main()是一個靜態上下文。只有一個,而在技術上有makeMoves()之一,例如,對於每個Ant對象。在Ant的實例上調用它們,或者將它們也設爲static。這是要點,只需查找關鍵字static,和/或上下文,範圍瞭解更多。

1

正如其他人指出的那樣,您正在編譯的代碼似乎與您發佈的代碼不匹配,因爲發佈的代碼包含的不僅僅是靜態訪問的其他錯誤。但是,我認爲你的基本問題(至少把問題看作是擺在你面前的問題)是你認爲你已經在Ant類中定義了一個實例變量,而實際上你沒有。您在Ant構造函數中爲其定義了一個局部變量,構造函數返回時立即拋棄該變量。

然後,由於floor類本身與您可能認爲可以容納Ant的變量之間存在命名衝突,因此您試圖調用floor.changeTileColor,認爲它會在Ant的實例上調用但是它編譯時似乎是對靜態方法的引用。這是因爲floor在這裏指的是floor類本身,而不是指一個變量持有一個實例。

要解決該問題,請在Ant類中創建一個floor實例變量,而不是僅在構造函數中(儘管如此,建議使用其他名稱,以避免更多命名衝突)。

+0

正確答案!另外,OP應將類的名稱從底層更改爲Floor以符合Java命名標準。 –

相關問題