尝试使用字符串数组从类创建新对象

时间:2016-01-14 18:19:56

标签: java android arrays class

我有一个名为Player的类,其中我有三个变量,其中一个是带有十个值的字符串数组(playerInv)。如何使用此Player类在主活动类中创建新的Player,数组中的每个索引都具有空值(“”)?

玩家类:

public class Player {

    private int playerPos;
    private int playerHP;
    private String playerInv[];

    Player(int startPos, int startHP, String[] newInventory[]) {
        playerPos = startPos;
        playerHP = startHP;
        playerInv = newInventory[10];
    }

    public int getPlayerPos() {
        return playerPos;
    }

    public void setPlayerPos(int playerPos) {
        this.playerPos = playerPos;
    }

    public int getPlayerHP() {
        return playerHP;
    }

    public void setPlayerHP(int playerHP) {
        this.playerHP = playerHP;
    }

    public String setPlayerInv(int pos) {
        return playerInv[pos];
    }

    public void setPlayerInv(String inventory) {
        for (int i = 0; i < 10; i++) {
            this.playerInv[i] = playerInv[i];
        }
    }
}

在主要活动中初始化播放器

public void setupPlayer()
{
    thePlayer = new Player(0,100,);
}

谢谢!

3 个答案:

答案 0 :(得分:2)

首先,类构造函数中存在错误。 如果要将String数组作为构造函数参数获取,它应该如下所示:

Player(int startPos, int startHP, String[] newInventory)
{
    playerPos = startPos;
    playerHP = startHP;
    playerInv = newInventory;
}

如果你希望playerInv始终是一个大小为10的字符串数组,它应该是这样的。

Player(int startPos, int startHP)
{
    playerPos = startPos;
    playerHP = startHP;
    playerInv = new String[10];
}

然后使用simple:

创建一个新的Player对象
thePlayer = new Player(0, 100);

重要的是,在第二种情况下,playerInv变量将包含对填充为null的String类型的数组的引用。所以表格看起来像这样:

[null, null, null, null, null, null, null, null, null, null]

如果您希望数组中填充空字符串(&#34;&#34;),如下所示:

   ["","","","","","","","","",""]

然后你还有至少2种方法:

Player(int startPos, int startHP)
{
    playerPos = startPos;
    playerHP = startHP;
    playerInv = new String[10];
    Arrays.fill(playerInv, "");
}

或者你可以使用这个构造函数:

Player(int startPos, int startHP, String[] newInventory)
{
    playerPos = startPos;
    playerHP = startHP;
    playerInv = newInventory;
}

在创建新的Player对象时执行此操作:

String[] inventory = new String[10];
Arrays.fill(inventory, "");
Player thePlayer = new Player(0, 100, inventory);

答案 1 :(得分:0)

在你的玩家构造函数中:

Player(int startPos, int startHP, String[] newInventory)
{
    playerPos = startPos;
    playerHP = startHP;

    if (newInventory == null)
    {
        playerInv = new String[10];
        for (int i = 0; i < playerInv.length; i++)
        {
            playerInv[i] = "";
        }
    }
    else
    {
        playerInv = newInventory;
    }
}

然后致电:

thePlayer = new Player(0,100,null);

希望它有所帮助...

答案 2 :(得分:0)

使用默认情况下创建所需内容的构造函数。