为什么我不能在while循环中访问变量

时间:2014-09-17 01:38:27

标签: java netbeans

由于某种原因,我无法从while循环中访问变量。我已经检查了其他帖子,但我似乎还是无法弄明白。

听到我的代码:

package pandacare;
import java.util.Random;
public class PandaCare {

Random r = new Random();

int HWT;

int hunger = 0;
int fun = 0;
int thirst = 0;
int energy = 0;
int hygiene = 0;
int points = 0;
int coins = 1000;
int total = hunger + fun +thirst + energy + hygiene;

public void hungerWait(){
    int Low = 5;
    int High = 30;
    HWT = r.nextInt(High-Low) + Low;

    try {
        Thread.sleep(5000);
    }
    catch(InterruptedException ex) {
        Thread.currentThread().interrupt();
    }
    hunger --;
}

    while(hunger > 0){
       hungerWait();
    }

}

1 个答案:

答案 0 :(得分:1)

请花一点时间仔细查看您的代码......

public class PandaCare {

    //...

    public void hungerWait() {
        int Low = 5;
        int High = 30;
        HWT = r.nextInt(High - Low) + Low;

        try {
            Thread.sleep(5000);
        } catch (InterruptedException ex) {
            Thread.currentThread().interrupt();
        }
        hunger--;
    }

    // This won't work, it's not a valid statement...
    while(hunger > 0){
       hungerWait();
    }

}

while(hunger > 0)不在任何方法之内。代码只能在静态块/初始化或方法中执行......

你需要将循环包含在某种方法中......

对于(粗略的)例子......

public class PandaCare {

    //...

    public void hungerWait() {
        int Low = 5;
        int High = 30;
        HWT = r.nextInt(High - Low) + Low;

        try {
            Thread.sleep(5000);
        } catch (InterruptedException ex) {
            Thread.currentThread().interrupt();
        }
        hunger--;
    }

    public void waitTillNoHungry() {        
        while(hunger > 0){
           hungerWait();
        }        
    }
}