由于某种原因,我无法从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();
}
}
花点时间仔细看看你的代码...
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();
}
}
}