非静态变量这不能从静态上下文中引用(non-static variable this cannot

2019-08-22 04:31发布

误差来源于此线BoardState ADDME =新BoardState();

出于某种原因,这是在指向非静态变量是“新”。 我不清楚新并不意味着是一个变量,而不是我如何修正这个错误。

寻找通过计算器记录该误差通常来自其通常通过使方法静态或完全绕过方法解决的非静态方法。 Ť

下面这段代码是引用前及本声明之后,到底是怎么回事。

public class IntelligentTicTacToe extends TicTacToe {

public class BoardState{
    public String TTTState;
    public int[][] defensiveOppsArray;
    public int[][] offensiveOppsArray;
    public String str;
    public int cnt;
}

public static ArrayList<BoardState> memory = new ArrayList<BoardState>();


public static boolean makeMove(){
    char[] oArray = new char[TicTacToeArray.length];
    int[][] defensiveOppsArray = new int[TicTacToeArray.length][TicTacToeArray.length];
    int[][] offensiveOppsArray = new int[TicTacToeArray.length][TicTacToeArray.length];
    int[][] sumOppsArray = new int[TicTacToeArray.length][TicTacToeArray.length];
    //converts our Array into a String
    String x = convertTTTArrayToString();

    //Goes through the conditions to see if we have it in memory or if we must go through all the conditions
    boolean matchFound = false;
        for(int i=0; i < memory.size(); i++){
            BoardState element = memory.get(i);
            if(element.str.equals(x)){
                System.out.println("Match Found");
                matchFound = true;
            }}
        if(!matchFound){
        BoardState addme = new BoardState();
        addme.str = x;
        addme.cnt = 1;
        memory.add(addme);

        }

} ....

Answer 1:

它不工作的原因是因为你的类BoardState是一种内在的,非静态,内部类IntelligentTicTacToe 。 这意味着,提到它的时候,你会提到的类的实例; 实例不能从静态上下文。

一个解决方案是声明类为:

public static class BoardState {

你可以阅读更多的内部类在这里 。



Answer 2:

不喜欢你这样做不能嵌套类。 有没有必要,所有它要做的是要求你在一个IntelligentTicTacToe实例的顶部,即创建一个BoardState对象,

BoardState addme = new IntelligentTicTacToe(). new BoardState();

但是这不应该是你的程序的要求。

解决方案:把它所属的BoardState类,在它自己的文件。 或使BoardState枚举,但随后它应该只持有常数。



文章来源: non-static variable this cannot be referenced from a static context