error: non-static variable this cannot be referenced from a static context
Player bot = new Player(-1,-1,0); //
The problem is I dont know where to put my class Player. If I would not been on codingame I would use a separate file for each java class… But here I’m lost I dont know if I should put the class outside of the class Main or not ?
I have been struggling for this syntax to work for the past hours, I dont know how to get this working
You can’t change CG main class. If the template is class Player {...} you can add nested class in Player but not add Player as inner class of something else.
Your code should looks like:
class Player {
public static void main(String args[]) {
...
Something something = new Something();
SomethingElse somethingElse = new Player().new SomethingElse();
}
private static class Something {
...
}
private class SomethingElse {
...
}
Or you can use directly Player and call new Player(...)
E.g :
class Player {
...
private Player(int x, int y, int backInTimeLeft){
...
}
public static void main(String args[]) {
Player player1 = new Player(1,0,2);
Player player2 = new Player(3,7,1);
}
}
Okay Duffy thank you very much ! I think my problem was thinking that I could change the class name that use CG by renaming the original Player class by a Main class …
Instance variables (variables defined in the class but not marked as static keyword) cannot be accessed from a static method without referencing an instance of the class. An attempt to use the variables and methods of the class which do not have the static modifier without creating an instance of the class is caught by the Java compiler at compile time and flagged as an error: Cannot Be Referenced From a Static Context . For ex. Java main() method cannot access a non-static member of its class. That means, public static void main(String[] args) is a static method.
Solutions:
Either make that variable static.
Make the calling function non-static.
Inside the calling function, create an object first and then access the non-static variable.