gpt4 book ai didi

java - 执行 while 循环时出现问题

转载 作者:行者123 更新时间:2023-12-02 05:29:48 28 4
gpt4 key购买 nike

我有一个用 swing 实现迷你游戏的程序,在主类中我有一个循环,用于监听游戏 map 中的 boolean 值。使用 while 实现的循环不会执行一条指令,如果它是唯一的一条指令,我不知道为什么。

我尝试添加一些其他指令来检查循环是否继续,并且效果很好,但是当我只添加我想要的 if 时,它不起作用。

public class ejecutor extends JFrame{
boolean ejecutando = true;

public ejecutor(){
mapa mapa = new mapa(); //the map of my game
setSize(665,690);
add(mapa);
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setVisible(true);
while(ejecutando){
if(mapa.todasComidas()){
//wLabel();
ejecutando=false;
System.out.println("You finished!!");
}
//If I put this println it works, if I only use the If, without any other instruction inside the while, it does not do anything at all
System.out.println("............");
}
}
//I execute the constructor in the main...

最佳答案

默认情况下,Java 中 Java 对象的 boolean 变量设置为默认值 false。查看您的代码 mapa.todasComidas(),您从未明确设置相同的内容。

现在在 while 循环中,您正在检查 todasComidas 方法是否返回 true ,但情况并非如此,因此永远不会重置相同的值,即执行内部语句的 if 条件。您的外部语句确实会被执行并在控制台上打印,因为它不受任何 if 条件的保护。

关于java - 执行 while 循环时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56207415/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com