I just started learning java and I’m working on a program. I’m getting an error here:
locationsOfCells = simpleDotCom.getLocationCells();
but I’m not sure what the error is. Eclipse say
Cannot make a static reference to the non-static method
getLocationCells()from the typesimpleDotCom
Can someone help me with this? What am I doing wrong?
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]);
}
}
}
The problem is you are calling the
getLocationCells()method as if it was a static method when in fact it is an instance method.You need to first create an object from your class like this:
and then call the method on it:
Incidentally, there is a widely followed naming convention in the Java world, where class names always start with a capital letter – you should rename your class to
SimpleDotComto avoid confusion.