2011-02-28 123 views
5

我想訪問java中if語句之外的變量。該變量是axeMinDmg。這是我的,但得到一個錯誤。我想minDmg = axeMinDmg。謝謝if語句之外的變量訪問

@SuppressWarnings("unused") 
    public static void main(String[] args) 
     throws IOException 
     { 


      int count = 1; 

    // start both with 1 point 
    int goodTotal = 50; 
    int monTotal = 50; 

    // set amount of money that Goodman has 
    int moneyAmt = 10; 




    // setting array for bat 

    int [] bat = {2, 4, 3}; 
    int batMinDmg = bat[0]; 
    int batMaxDmg = bat[1]; 
    int batCost = bat[2]; 

    //setting array for axe 
    int [] axe = {4, 6, 6}; 
    int axeMinDmg = axe[0]; 
    int axeMaxDmg = axe[1]; 
    int axeCost = axe[2]; 

    //setting array for sword 

    int [] sword = {6, 8, 10}; 
    int swordMinDmg = sword[0]; 
    int swordMaxDmg = sword[1]; 
    int swordCost = sword[2]; 



    // ask if Goodman would like to purchase a weapon 
    System.out.println("Would you live to purchase a weapon (YES OR NO): "); 
    Scanner sc = new Scanner(System.in); 
    String name = sc.next(); 


    if (name.equals("yes")){ 
     System.out.println("Select Your Weapon \n axe \n bat \n sword : \n "); 

     Scanner wc = new Scanner(System.in); 
     String weapon = wc.next(); 
     int minDmg = axeMinDmg; 

    if(weapon.equals("axe")){ 
    int minDmg = axeMinDmg; 
    } else { 
     System.out.println(); 
} // close if statement  

回答

8

您需要定義if語句之外的變量才能在外部使用它。

2

只是聲明整數if語句外:

int minDmg; 
if(weapon.equals("axe")){ 
    minDmg = axeMinDmg; 
} else { 
    System.out.println(); 
System.out.println("Can access variable: " + minDmg); 
+0

是有聲明全局變量與範圍來訪問變量的方式 – earnest 2011-02-28 19:29:09

+0

我不確定我瞭解你的問題。 – 2011-02-28 19:39:09

4

在Java中,變量的範圍內,定義。這裏的範圍是if塊。所以如果你在if塊之外聲明它,它將在封閉方法範圍中可用。

0

如果要將變量分配給if-else塊之外,可以使用運算符代表的ternary operator

例如,標準的if-else Java表達式:

int money; 
if (shouldReceiveBonus()) { 
    price = 100; 
} 
else { 
    price = 50; 
} 

隨着三元操作等效於:

int money = shouldReceiveBonus() ? 100 : 50;