非静态变量,不能从静态上下文引用

时间:2013-04-12 02:59:56

标签: java static non-static

错误来自此行      BoardState addme = new BoardState();

由于某种原因,它指向的非静态变量是“new”。我不清楚如何修复此错误,因为新的并不意味着变量,而不是。

查看stackoverflow记录此错误通常来自非静态方法,通常通过使方法静态或完全绕过该方法来解决。 Ť

以下代码用于引用此声明之前和之后的内容。

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);

        }

} ....

2 个答案:

答案 0 :(得分:18)

它不起作用的原因是因为您的类BoardStateIntelligentTicTacToe内部的内部非静态类。这意味着在引用它时,您将引用该类的实例;静态上下文中没有实例。

一种解决方案是将该类声明为:

public static class BoardState {

您可以阅读有关内部课程here的更多信息。

答案 1 :(得分:2)

不要像你一样嵌套课程。没有必要,它要做的就是要求你在IntelligentTicTacToe实例之上创建一个BoardState对象,即

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

但这不应该是您的计划的要求。

解决方案:将BoardState类放在它自己的文件中。 或者使BoardState成为枚举,但它应该只保留常量。