2016-08-28 42 views
0

我有一個方法processInput當它是用戶的轉向時被激活,變量prompt讓我知道用戶在遊戲的哪個點。事件驅動的基於回合的文本遊戲,創建一個對象

所以我有一個提示「找到一個有價值的對手新聞F」。如果用戶按下「F」,我會生成一個對象,然後隨機讓用戶/對手互相攻擊。之後,當用戶再次轉向時,它會提示「按A攻擊」,但由於前一個提示(if)創建了一個對象,編譯器不知道它是否被執行以允許我引用該對象。

processInput的最後一個if子句中,行player.attack(e);,e可能尚未初始化,因此我不知道如何解決此問題。

public class inputListener implements ActionListener{ 
     @Override 
     public void actionPerformed(ActionEvent ae) { 
      String inputLog = input.getText(); 
      input.setText(""); 
      console.append(input + "\n"); 
      processInput(inputLog);  
     } 

     void processInput(String inputLog){ 
      input.setEnabled(false); 
      Enemy e; 
      if(prompt.startsWith("What is your name")){ 
       if(inputLog.isEmpty()){ 
        player.setName("Bob"); 
        console.append("...\nYour name therefore is Bob"); 

       }else{ 
        player.setName(inputLog); 
        console.append("Alright "+player.getName()+"...\n"); 
       } 
       choosePath(); 
      }else if(prompt.startsWith("If you wish to find a worthy opponent")){ 
       if(inputLog.equalsIgnoreCase("f")){ 
        e = generateEnemy(); 
        console.setText(""); 
        console.append(e.getClass().getSimpleName()+" Level: "+e.getLvl()); 
        console.append("\nHP: "+e.getHP()); 
        console.append("\n\n\n"); 

        if(Math.random()>0.49){ 
         userTurn("Press A to attack"); 
        }else{ 
         e.attack(player); 
         if(!player.isDead()){ 
          userTurn("Press A to attack"); 
         } 
        }     
       } 
      }else if(prompt.startsWith("Press A to attack")){ 
       player.attack(e); 
       if(!player.isDead()||!e.isDead()){ 
        e.attack(player); 
        userTurn("Press A to attack"); 
       }else if(e.isDead()){ 
        console.append("\nYou have killed "+e.getClass().getSimpleName()+"!\n\n"); 
        choosePath(); 
       } 

      } 
     } 

    } 

回答

1

您如何提示用戶輸入?如果e爲空,你能排除「攻擊」選項嗎?否則,如果他們選擇「攻擊」而不是跳過它,如果e爲空。

} else if(prompt.startsWith("Press A to attack")) { 
    if (e != null) { // enemy might not be initialized yet 
     player.attack(e); 
     if (!player.isDead()||!e.isDead()) { 
      e.attack(player); 
      userTurn("Press A to attack"); 
     } 
     else if(e.isDead()) { 
      console.append("\nYou have killed "+e.getClass().getSimpleName()+"!\n\n"); 
      choosePath(); 
     } 
    } 
} 
+0

e!= null要求我在processinput狀態的開始時敵人e = null;這將永遠把它變爲空,並摧毀我的對象。我提示用戶輸入的方式void userTurn(String prompt){console.append(this.prompt = prompt); input.setEnabled(true); input.requestFocus(); } – Higeath

+0

檢查null不應該要求您將其設置爲null。你已經在上面聲明它,所以它被初始化爲null。 – pmcevoy12

+0

它確實顯示了'變量e可能未被初始化' – Higeath