Set elements of a java array from another class or file



I’m making a game right now and I’m trying to setup a CreatePlayer method.

In the main class, I take the Player class as an object to get its variables, methods ect.

package com.deud07.main;

import com.deud07.player.Player;

public class Main {
    
    public static Player player = new Player("Bob", 86, null);
    
    public static void main(String[] args) {
        System.out.println(player.Position);
    }
}

The 3rd parameter of Player is the Position, which is an array. The problem I’m having is that I’m not sure how to set each element of the array without writing:

position[0] = 1f;
position[1] = -6f;
position[2] = 0f;

The code for Player:

package com.deud07.player;

public class Player {
    public static String Name;
    public static int ID;
    
    public static float x;
    public static float y;
    public static float z;
    public static float[] Position = {x, y, z};
    
    public Player(String name, int id, float[] pos) {
        Player.Name = name;
        Player.ID = id;
        Player.Position = pos;
    }
    
    public void createPlayer(String name, int id, float[] pos) {
        Player player = new Player(name, id, pos);
        
        player.Name = name;
        player.ID = id;
        player.Position = pos;
    }
}

Any solutions? And while you’re at it, anything I can do to fix up my code?

Answer

I believe you’re asking for a shorthand method. You might also find them as “one liners”. The way to initiate an array in one line without a variable is as follows:

Player player = new Player("Bob", 86, new float[]{1f, -6f, 0f});

As for “fixing your code”, it goes outside of the actual question you’ve posted. Two things I can say are

  1. Java conventions state that variables must be camel case. So your Player class’ attributes should be name, id and position.
  2. Your method createPlayer() does exactly the same the constructor does, thus it is not necessary. To create a new Player, just use… well, new Player().

Also, x, y and z are kind of useless. If you need x for example, just use position[0] instead.



Source: stackoverflow