无法纠正我的java程序

时间:2012-09-07 12:12:07

标签: java arrays

我刚开始学习java而且我正在研究一个程序。我在这里收到错误:

locationsOfCells = simpleDotCom.getLocationCells();

但我不确定错误是什么。 Eclipse说

  

无法对非静态方法进行静态引用   来自getLocationCells()

类型的simpleDotCom

有人可以帮我吗?我做错了什么?

public class simpleDotCom {
    int[] locationsCells;

    void setLocationCells(int[] loc){
        //Setting the array
        locationsCells = new int[3];
        locationsCells[0]= 3;
        locationsCells[1]= 4;
        locationsCells[2]= 5;
    }

    public int[] getLocationCells(){

        return locationsCells;

    }
}

public class simpleDotComGame {

    public static void main(String[] args) {
        printBoard();
    }

    private static void printBoard(){
        simpleDotCom theBoard = new simpleDotCom();
        int[] locationsOfCells; 
        locationsOfCells = new int[3];
        locationsOfCells = theBoard.getLocationCells();

        for(int i = 0; i<3; i++){
            System.out.println(locationsOfCells[i]);
        }

    }

}

7 个答案:

答案 0 :(得分:3)

问题是你正在调用getLocationCells()方法,就好像它是一个静态方法,而实际上它是一个实例方法。

您需要先从类中创建一个对象,如下所示:

simpleDotCom myObject = new simpleDotCom();

然后调用它上面的方法:

locationsOfCells  = myObject.getLocationCells();

顺便提一下,Java世界中有一个广泛遵循的命名约定,其中类名始终以大写字母开头 - 您应该将类​​重命名为SimpleDotCom以避免混淆。

答案 1 :(得分:1)

您正在以静态方式尝试getLocationCells。您需要先创建simpleDotCom的实例:

simpleDotCom mySimpleDotCom = new simpleDotCom();       
locationsOfCells = mySimpleDotCom.getLocationCells();

BTW班级名称始终以大写字母开头。这有助于消除作为成员方法访问方法的困惑。

更新

要从更新后的静态方法进行访问,您还需要将theBoard声明为static变量:

static simpleDotCom theBoard = new simpleDotCom();

答案 2 :(得分:1)

您正尝试从main方法引用非静态方法。这在java中是不允许的。您可以尝试将simpleDotCom类设置为静态,以便您可以访问该类的方法。

答案 3 :(得分:1)

simpleDotCom obj = new simpleDotCom();
locationsOfCells = obj.getLocationCells();

此外,您的班级名称应以大写字母

开头

答案 4 :(得分:0)

您正试图从静态上下文访问普通的非静态方法,但它不起作用。

您可以从尝试访问getLocationCells()的例程中删除静态字,或者通过在其声明中添加静态字来使getLocationCells()静态。

答案 5 :(得分:0)

使simpleDotCom的字段和方法也是静态的,或者创建simpleDotCom的实例并访问实例的方法。

答案 6 :(得分:0)

您的代码有更多错误。

  1. 非静态方法无法使用类名调用。因此,尝试使用object调用getLocationCells()。

    simpleDotCom obj = new simpleDotCom(); obj.getLocationCells()

  2. 接下来你将获得空指针异常。您尝试在初始化之前打印locationsOfCells值。因此,请在打印值之前尝试调用setLocationCells()方法。

  3. Ur方法定义void setLocationCells(int [] loc)。这里你有参数loc但你没有使用方法块中的任何位置。所以请注意处理方法参数。