如何从数组中获取特定参数?

时间:2019-07-09 21:29:56

标签: java arrays

我正在尝试为游戏制作一个关卡系统,却无法弄清楚如何在我的一生中做到这一点。我创建了一个数组,并为其中的每个项目分配了2个参数。我该如何处理第二个参数?

public static int currentLevel = 0;
public static Level levels[] = new Level[100];

int t = 250;

public void initLevels() {
    for (int i = 0; i < 100; i++) {
        levels[i] = new Level(i, t * i);
    }
}


public static void checkXP() {

    currentLevel = PlayerData.PlayerLevel;

    if(PlayerData.CurrentXP > levels[currentLevel] /*I want to 
            get the second arg here*/) {
        levelUp();
    }
}

public static void levelUp() {
    PlayerData.PlayerLevel = PlayerData.PlayerLevel + 1;
    System.out.println(PlayerData.PlayerLevel);
}

1 个答案:

答案 0 :(得分:0)

在程序中,将Level对象而不是数组存储在levels数组变量中。对象具有一系列不能由索引(例如数组罐头)直接访问的属性。

例如:

public class Foo {
    private int attribute;

    public Foo(int attribute) {
        this.attribute = attribute;
    }

    public int getAttribute() {
        return attribute;
    }
}

在此示例中,类Foo具有一个属性attribute。可以通过调用函数getAttribute来访问它,该函数将允许程序的其他部分访问该对象所包含的数据。

在您的情况下,您需要像已经完成的那样访问levels数组中的特定对象,然后使用检索属性的函数调用访问Level对象的属性您需要。

levels[currentLevel].getSecondAttribute()

有关访问对象属性的更多信息,请参见here

希望这会有所帮助

相关问题