![](/img/trans.png)
[英]Why can't I reach the correct solution in my file splitting program (Java)?
[英]Can't correct my java program
我刚开始学习Java,正在研究程序。 我在这里遇到错误:
locationsOfCells = simpleDotCom.getLocationCells();
但我不确定是什么错误。 Eclipse说
无法从类型
simpleDotCom
静态引用非静态方法getLocationCells()
有人可以帮我弄这个吗? 我究竟做错了什么?
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]);
}
}
}
问题是您实际上在调用getLocationCells()
方法,就像它是一个静态方法一样,而实际上它是一个实例方法。
您需要首先从您的类中创建一个对象,如下所示:
simpleDotCom myObject = new simpleDotCom();
然后在其上调用方法:
locationsOfCells = myObject.getLocationCells();
顺便说一句,在Java世界中,有一个广泛遵循的命名约定,其中类名始终以大写字母开头-您应将类重命名为SimpleDotCom
以避免混淆。
您正在以静态方式尝试getLocationCells
。 您需要首先创建simpleDotCom
的实例:
simpleDotCom mySimpleDotCom = new simpleDotCom();
locationsOfCells = mySimpleDotCom.getLocationCells();
BTW类别名称始终以大写字母开头。 这将有助于消除将方法作为成员方法访问的困惑。
更新:
要从更新后的静态方法访问,还需要将theBoard
声明为static
变量:
static simpleDotCom theBoard = new simpleDotCom();
您正在尝试从main方法引用非静态方法。 在Java中是不允许的。 您可以尝试将simpleDotCom类设为静态,以便您可以访问该类的方法。
simpleDotCom obj = new simpleDotCom();
locationsOfCells = obj.getLocationCells();
而且您的班级名称也应该以大写字母开头
您正在尝试从静态上下文访问普通的非静态方法,该方法不起作用。
您可以从尝试访问getLocationCells()
的例程中删除该静态词,也可以通过在其声明中添加静态词来使getLocationCells()
成为静态。
也可以使simpleDotCom的字段和方法静态化,或者创建simpleDotCom的实例并访问该实例的方法。
您的代码还有更多错误。
非静态方法无法使用类名调用。 因此,请尝试使用对象调用getLocationCells()。
simpleDotCom obj = new simpleDotCom(); obj.getLocationCells()
接下来,您将获得空指针异常。 U尝试在初始化之前打印locationsOfCells值。 因此,尝试在打印值之前调用setLocationCells()方法。
Ur方法定义void setLocationCells(int [] loc)。 在这里,您具有参数loc,但是您在方法块中未使用任何位置。 因此请注意处理方法参数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.