gpt4 book ai didi

java - 如何更改不同类的字符串数组的值?

转载 作者:行者123 更新时间:2023-12-01 10:35:02 25 4
gpt4 key购买 nike

这可能是一个非常简单的问题,但我似乎无法在 Google 上找到合适的答案。我有一个名为 Player 的类,它有一个名为 playerInv 的字符串数组,大小为 10。

在我的主 Activity 类中,我想运行 for 循环来确定数组中第一个为空的索引 ("")。然后我想用一个新字符串填充它,然后终止循环。我该怎么做呢?

很抱歉问了这个菜鸟问题。就像我说的,我尝试过 Google,但没有成功!

For 循环:

    String playerInvTemp[] = thePlayer.getPlayerInv; ERROR -- cannot resolve getPlayerInv
for (int i=0; i < playerInvTemp.length; i++)
{
if ((!playerInvTemp[i].isEmpty()) || playerInvTemp[i] == null)
{
setPlayerInv("Blood Essence", i); ERROR cannot resolve setPlayerInv
//invText.setText();
Blood = true;
break;
}
}

玩家等级:

公共(public)类玩家{

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

Player(int startPos, int startHP, String[] newInventory)
{
playerPos = startPos;
playerHP = startHP;
playerInv = newInventory;
}
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 getPlayerInv(int pos)
{
return playerInv[pos];
}

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

public void setPlayerInv(String val, int index)
{
this.playerInv[index] = val;
}

public String getPlayerInv()
{
return this.playerInv; *//this gives error "Incompatible types. Required java.lang.string, found java.lang.string[]"*
}

}

最佳答案

这样做

Player类中添加这两个方法

public void setPlayerInv(String val, int index) 
{
this.playerInv[index] = val;
}

public String[] getPlayerInv()
{
return this.playerInv;
}

然后像这样改变你的for循环

String playerInvTemp[] = thePlayer.getPlayerInv();
for (int i=0; i < playerInvTemp.length; i++)
{
if (!playerInvTemp[i].isEmpty()) || playerInvTemp[i] == null)
{
setPlayerInv("Blood Essence", i);
//invText.setText();
Blood = true;
break;
}
}

关于java - 如何更改不同类的字符串数组的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34809958/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com