1

I'm making a program in java to register players and add them in an arraylist. My method for adding players is this:

void registerNewPlayer() {
        System.out.print("Name?> ");
        String name = input.nextLine();
        System.out.print("Game?> ");
        String game = input.nextLine();
        System.out.print("Age?> ");
        int age = input.nextInt();
        Player player = new Player(name, game, age);
        players.add(player);
    }

my problem is that i don't know where to put

 ArrayList<Player> players = new ArrayList<>();

if i have it in main, the method doesn't know what players is, but if i have it in the class i get a "Cannot make a static reference to the non-static field players" exception, when i try to print it from main. What's the best way of solving this.

Update: thanks for the help, i realized that since my command loop is already running on an instanced version of my class there is actually no problem, there was only a problem when i tried to test my method outside the instanced command loop.

geisterfurz007
  • 5,292
  • 5
  • 33
  • 54
Jhilsara
  • 21
  • 5

4 Answers4

2

If you'd like to have it at the class level, escape the static context.

public class YourClass {
  ArrayList<Player> players = new ArrayList<>();

  public static void main(String[] args) {
    new YourClass(); // or YourClass yourClass = new YourClass();
  }

  // Create an instance of YourClass to leave the static context
  public YourClass() {
    registerNewPlayer();
  }

  public void registerNewPlayer() {
    System.out.print("Name?> ");
    String name = input.nextLine();
    System.out.print("Game?> ");
    String game = input.nextLine();
    System.out.print("Age?> ");
    int age = input.nextInt();
    System.out.print("Weight?> ");
    int weight = input.nextInt();
    Player player = new Player(name, game, age, weight);
    players.add(player);
  }
}
sleepToken
  • 1,866
  • 1
  • 14
  • 23
  • in the main, you're using shorthand and mean something like YourClass yourClass = new YourClass(); ? – Jeremy Kahan Jan 14 '20 at 12:27
  • @JeremyKahan I agree that instantiating this way limits some of the functionality - but it would still solve the *static* issue. I updated to reflect your comment – sleepToken Jan 14 '20 at 12:32
0

I thinik this is the best solution for your problem. I hope it helps :)

  1. Your Player class:

    public class Player {

    private static ArrayList<Player> _players = new ArrayList<Player>();

    private String name;
    private String game;
    private int age;
    private int weight;

    public Player(String name, String game, int age, int weight){
        this.name = name;
        this.game = game;
        this.age = age;
        this.weight = weight;            
    }

     public static void AddPlayer(Player player){
        _players.add(player);
    }
    public static ArrayList<Player> getPlayers(){
        return _players;
    }

}

  1. Now you can create some players and get them as follow:

... main ...
  .
  .
  .    
    Player p1 = new Player("Name1", "Game1", 20, 70);
    Player p2 = new Player("Name2", "Game2", 30, 80);
    Player p3 = new Player("Name2", "Game3", 25, 73);
    Player.AddPlayer(p1);
    Player.AddPlayer(p2);
    Player.AddPlayer(p3);
    ArrayList<Player> allPlayers = Player.getPlayers();
  .
  .
  .

Let me know if it is working for you !

Adrian Efford
  • 473
  • 3
  • 8
  • Constructors with side effects like this are probably not a good idea. Instead have the list outside of the Player class (where it doesn't belong in the first place keeping Single Responsibility Principle in mind) and add the Players after you created them. – geisterfurz007 Jan 14 '20 at 13:23
  • Yes you are right. Maybe the best solution is to create a mehtod named AddPlayer so you can create a new Player via constructor and add it using this new function. What do you think? – Adrian Efford Jan 14 '20 at 13:35
  • I think that the Player class is not a good place to store all players in. In this case it should be enough to have the list in the main method. So (sorry for the poor formatting; doesn't work well in comments): `main(String[] args) { List players = new ArrayList<>(); Player p1 = new Player("Name1", "Game1", 20, 70); players.add(p1); }` which brings a few improvements compared to how it is now: No need for static variables and methods (which are not a bad thing per se but should be avoided in many cases), uses an interface (List) instead of a set implementation (ArrayList in your case) – geisterfurz007 Jan 14 '20 at 14:01
  • as type (which is a good practice) and it keeps tracking the players out of what should be a pure data class. You can keep the players in another place outside the main method for sure but ideally you don't put them into the Player class. If you have more questions, feel free to join me in the Java chat (shameless plug; it's linked in my profile). You will need at least 20 reputation for that but you will get there in no time with a few edits :) – geisterfurz007 Jan 14 '20 at 14:03
  • I will keep that in mind. Thank you for your time ! – Adrian Efford Jan 14 '20 at 14:07
0

The error you get is because you are trying to access a non-static variable (i.e. a value or object that exists only in instances of that class) from outside of such an instance. What you can do is to create an object of that class to be able to access the players through it:

public class Demo {

    private List<Player> players = new ArrayList<>();

    public static void main(String[] args) {
        Demo demo = new Demo();
        demo.registerNewPlayer();
        System.out.println(demo.players);
    }

    private void registerNewPlayer() {
        System.out.print("Name?> ");
        String name = input.nextLine();
        System.out.print("Game?> ");
        String game = input.nextLine();
        System.out.print("Age?> ");
        int age = input.nextInt();
        Player player = new Player(name, game, age);
        players.add(player);
    }
}

By creating an object of the class and executing the method as well as access the variable through it, allows you to do what you want (if I understood correctly that is).

Further reading material:

Java: when to use static methods
Type List vs type ArrayList in Java (you may have noticed that I changed the type of players to List<Player> from ArrayList<Player>)
What is the difference between public, protected, package-private and private in Java? (you may have noticed the private keyword on the list and the method)

geisterfurz007
  • 5,292
  • 5
  • 33
  • 54
-3

Globally declare the list.

ArrayList<Player> players = new ArrayList<>();
geisterfurz007
  • 5,292
  • 5
  • 33
  • 54
  • 2
    Globally? What do you mean by that? You clearly didn't test this because it won't work. Not to mention if *Globally* means at the class level - OP stated *in their question* that they tried this already and it gave them a static reference error. – sleepToken Jan 14 '20 at 14:10