2015-06-19 47 views
0

我試圖做一個非常簡單的遊戲(即使沒有界面)。你應該輸入你想要做什麼動作(攻擊或阻止),但是我沒有最好的時間試着去理解如何去做。我希望它是這樣的:如果用戶類型攻擊的行爲是一個行爲,它是否比另一個阻止,是否我想讓它回到問什麼要做。如何根據用戶輸入實現不同的動作

import java.util.Scanner; 
public class Game { 
    public static void main(String[] args){ 
     int hp = 10; //Not used yet 
     int enemy_hp = 10; 
     String attack; 
     String block; 
    int enemy_action = (int) (Math.random() * 1); //Not used yet 
    int your_block_chance1 = (int) (Math.random() * 1);//Not used yet 
    Scanner userInput = new Scanner (System.in); 
    System.out.println("It is your turn, attack or try to block"); 
    String action = userInput.next(); 
    System.out.println(action); 
    if (action.equals(attack)){ 
     System.out.print("You attacked your enemy and "); 
     int enemy_block_chance1 = (int) (Math.random() * 3); 
     if (enemy_block_chance1 == 1) { 
      System.out.print("he blocked it"); 
     } 
     else if (enemy_block_chance1 != 1){ 
      enemy_hp = enemy_hp - 2; 
      System.out.print("managed to hit, now his hp is " +enemy_hp); 
     } 
    } 
    else if (action.equals(block)){ 

    } 
    } 
} 

回答

0

變化:

if (action.equals(attack)) 

到:

if (action.equals("attack")) 

(併爲阻止操作檢查相同)

目前,您的字符串攻擊尚未確定等於「攻擊」,因爲它沒有被初始化,所以它只是一個空字符串。

注意:您還應該使用try/catch塊來包圍代碼以實現異常處理(例如,當用戶輸入整數時,程序不會崩潰)。

相關問題