从另一个 class 或文件中设置 java 数组的元素

Set elements of a java array from another class or file

我正在制作游戏,我正在尝试设置 CreatePlayer 方法。

在主体class中,我将Player class作为一个对象来获取它的变量,方法等

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);
    }
}

Player的第三个参数是Position,是一个数组。 我遇到的问题是我不确定如何在不写的情况下设置数组的每个元素:

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

播放器代码:

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;
    }
}

有什么解决办法吗?当你在做的时候,我能做些什么来修复我的代码?

我相信您要求的是 shorthand 方法。您可能还会发现它们是“一条线”。不带变量一行初始化数组的方法如下:

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

至于“修正你的代码”,它超出了你发布的实际问题。我可以说的两件事是

  1. Java 约定声明变量必须是驼峰式大小写。所以你的 Player class' 属性应该是 name, idposition.
  2. 您的方法 createPlayer() 与构造函数完全相同,因此没有必要。要创建一个新的 Player,只需使用...好吧,new Player().

此外,xyz 有点没用。例如,如果您需要 x,只需使用 position[0] 即可。