if语句之外的变量访问

时间:2011-02-28 18:47:55

标签: java if-statement

我试图在java中的if语句之外访问变量。变量是axeMinDmg。这是我有,但得到一个错误。我想要minDmg = axeMinDmg。感谢

    @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    

4 个答案:

答案 0 :(得分:8)

您需要在if语句之外定义变量才能在外部使用它。

答案 1 :(得分:4)

在Java中,变量是在范围内定义的。这里的范围是if块。因此,如果您在if块之外声明它,它将在封闭方法范围内可用。

答案 2 :(得分:2)

只需声明if语句之外的整数:

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

答案 3 :(得分:1)

如果要将变量分配给if-else块之外,可以使用由:运算符表示的ternary operator

例如,标准的if-else Java表达式:

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

使用三元运算符相当于:

int money = shouldReceiveBonus() ? 100 : 50;