这可能是一个非常简单的问题,但我似乎无法在Google上找到合适的答案。我有一个名为Player的类,它有一个名为playerInv的String数组,大小为10.
在我的主活动类中,我想运行一个for循环来确定数组中第一个为空的索引("")。然后我想用新字符串填充它,然后终止循环。我该怎么做呢?
对于这个不起眼的问题感到抱歉。就像我说的那样,我试过谷歌无济于事!
For Loop:
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 class Player {
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[]"*
}
}
答案 0 :(得分:1)
这样做
在Player
class
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;
}
}
答案 1 :(得分:0)
这里有一堆问题,.length()
对数组无效,应该是.length
。
`for (int i=0; i<thePlayer.getPlayerInv(i).length(); i++)`
你很可能意味着null
或至少需要检查它,在这里你需要[]
而不是()
:
if (thePlayer.getPlayerInv[i] == "" or theplayer.getPlayerInv[i] == null)
这是完全错误的,事实上你需要发布你的代码和错误,你有很多问题,应该从学习一些关于Java的基础知识开始。
尝试一些初学者教程(https://www.google.com/search?q=java+tutorials&ie=utf-8&oe=utf-8)。您有很多的语法和逻辑错误。
答案 2 :(得分:0)
您是否运行构造函数player()??
的实例我做了
Player a=new Player();
a.getPlayerInv(0)
并且工作正常。