如何在if语句中定义变量并在该语句之外使用它们?

时间:2014-03-01 22:29:22

标签: java variables if-statement

if (difficulty.equals("easy")) {
    System.out.println("Setting stats to " + difficulty);
    int food = 3000;
    int foodperson = 5;
    int energy = 0;
    int hulltotal = 5000;
    int hullhealth = 5000;
    int enemy1basehealth = 10;
    int enemy1basedamage = 1;
    int daystillevents = 80;
}

System.out.println("food: " + food);

当您尝试打印食物变量时,会出现错误。你怎么做到这一点,当你试图打印它,它会成功打印正确的信息?

2 个答案:

答案 0 :(得分:1)

在if语句之外定义它们。

int food = 0;
int foodperson = 0;
int energy = 0;
int hulltotal = 0;
int hullhealth = 0;
int enemy1basehealth = 0;
int enemy1basedamage = 0;
int daystillevents = 0;

if(difficulty.equals("easy")){
    System.out.println("Setting stats to " + difficulty);
    food = 3000;
    foodperson = 5;
    energy = 0;
    hulltotal = 5000;
    hullhealth = 5000;
    enemy1basehealth = 10;
    enemy1basedamage = 1;
    daystillevents = 80;
}
System.out.println("food: " + food);

答案 1 :(得分:1)

你做不到。变量仅在其定义的范围内可用。

但是,你确实有几个选择。您可以在if语句中打印。

if(difficulty.equals("easy")){
    System.out.println("Setting stats to " + difficulty);
    int food = 3000;
    int foodperson = 5;
    int energy = 0;
    int hulltotal = 5000;
    int hullhealth = 5000;
    int enemy1basehealth = 10;
    int enemy1basedamage = 1;
    int daystillevents = 80;

    System.out.println("food: " + food);
}

或者您可以在if语句之外定义食物。此选项更灵活,因为您可以在当前范围内的任何地方访问食物,但如果您在其他地方不需要它,请使用第一个选项。在您需要使用它们的范围内定义变量通常是一种很好的做法。

int food = 0;

if(difficulty.equals("easy")){
    System.out.println("Setting stats to " + difficulty);
    food = 3000;
    int foodperson = 5;
    int energy = 0;
    int hulltotal = 5000;
    int hullhealth = 5000;
    int enemy1basehealth = 10;
    int enemy1basedamage = 1;
    int daystillevents = 80;
}
System.out.println("food: " + food);