Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
565 views
in Technique[技术] by (71.8m points)

java - non-static variable this cannot be referenced from a static context

The error comes from this line BoardState addme = new BoardState();

For some reason the non-static variable that it is pointing at is "new". I am unclear of how I can fix this error as new is not meant to be a variable, and is not.

Looking through the stackoverflow records this error usually comes from a non-static method which is usually solved by making the method static or bypassing the method entirely. T

This code below is to reference what is going on before and after this statement.

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

        }

}....

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The reason it doesn't work is because your class BoardState is an inner, non-static, class inside of IntelligentTicTacToe. This means that when referring to it, you'll be referring to an instance of the class; the instance isn't available from a static context.

One solution is to declare that class as:

public static class BoardState {

You can read more on inner classes here.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...