非静态变量,不能从静态上下文引用 [英] non-static variable this cannot be referenced from a static context

查看:94
本文介绍了非静态变量,不能从静态上下文引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

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

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

        }

} ....

推荐答案

它不起作用的原因是因为你的类 BoardState 是一个内在的,非静态的,类 IntelligentTicTacToe 。这意味着在引用它时,您将引用该类的实例;该实例在静态上下文中不可用。

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.

这篇关于非静态变量,不能从静态上下文引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆