2016-01-23 68 views
0

我的個人迷你項目是在這裏學習數組,通過創建一個對象數組來做一個略微大的跳躍。我想要做的是一個小型RPG系統,我創建一個名爲怪物的類並給它一個參數,並創建一個Monster類的對象數組。到目前爲止,我相信我在下面列出的主要方法類(Exec_Monster)中創建了Monster類和Object of Arrays。如何在其他類中使用多個參數和訪問對象(及其值)創建類對象數組?

最初我花了一段時間,但我終於到了可以創建怪物陣列並在Main類中訪問它們的地步。但是有沒有辦法讓我創建這個對象數組並訪問另一個類的每個對象(以及它們各自的值)?例如,我會創建一個「戰鬥」類,然後我會從怪物的對象中提取「健康」值。

我是新來的陣列,但我在過去的兩週裏有過一些課程的經驗。

類:

public class Monster 
{ 
    public int hp; 
    public String n; 
    public Monster(String name,int health){ 
     n=name; 
     hp=health;   
    } 
    public int returnHealth(){ 
     return hp; 
    } 
    public String returnName(){ 
     return n; 
    } 
} 

Exec_Monster:

public class Exec_Monster{ 
public static void main(String args[]) 
    {//Define Monsters 
     Monster[] monsterid=new Monster[]{ 
     new Monster("Goblin",10), 
     new Monster("Elf", 8), 
     new Monster("Ant", 3), 
     new Monster("Worm", 2), 
     new Monster("Black Widow",6)}; 

     Random chooser; 
     int chosenmonster=(chooser.nextInt()*5); 
    //Start 
     //while (Battle.wonloss==true) {    
      // Battle.battle(); 
     } 
    } 

回答

0

你需要的怪物進入戰役對象以某種方式(或到您進入戰役另一個對象目的)。你可以將它作爲參數傳遞給一個方法,但在一個面向對象的世界裏,如果怪物真的屬於一場戰鬥,你可以將它們傳遞給構造函數,並將它們用於戰鬥類的所有方法中。

例子:

public class Battle { 
    private Monster[] monsters; 
    private boolean wonloss; 

    public Battle(Monster[] monsters) { 
     this.monsters = monsters; 
    } 

    public boolean isWonloss() { 
     return wonloss; 
    } 

    public void battle() { 
     // Do something with monsters, 

     // and then check if there is any life left in the monsters 
     int totalHp = 0; 
     for (Monster monster : monsters) { 
      totalHp += monster.hp; 
     } 
     if (totalHp == 0) { 
      wonloss = false; 
     } 
    } 
} 

那麼你的主要方法的「戰鬥」的部分看起來像:

// Start 
Battle battle = new Battle(monsterid); 
while (battle.isWonloss()) { 
    battle.battle(); 
} 
+0

有趣,我想在這裏一起跟隨,我是新來的這部分: '(怪物怪物:怪物){' '你能解釋括號內發生了什麼嗎? 在另一個類中創建對象的私有數組是將怪物列表傳遞給其他類的方式? – MrOats

+0

@MrOats這是一個for-each循環,基本上這意味着「對於陣列中的每個怪物怪物」怪物「。有關for-each循環的詳細信息,請參閱此文章:http://stackoverflow.com/questions/85190/how-does-the-java-for-each-loop-work –

+0

對不起,我對我的評論有問題,我只是修復。 – MrOats

相關問題