2013-09-29 67 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命名标准。 –

相关问题