gpt4 book ai didi

java - True boolean while 语句在嵌套 if 中不退出循环

转载 作者:行者123 更新时间:2023-12-01 13:57:29 24 4
gpt4 key购买 nike

当我在循环内设置 while1 = false 时,其中 while1 的值为 true 并且循环条件为 while(while1) ,它应该退出循环。但在嵌套的 if 语句中,它似乎并没有这样做。

package javanotes;
import java.util.Scanner;

public class EggsCount {

static Scanner var1 = new Scanner(System.in);

public static void main (String[] args){

int eggNumber;
int eggsGross;
int eggsDozen;
int eggsSingle;
int eggsGrossRemainder;
int eggsDozenRemainder;
boolean while1 = true;
boolean while2 = true;

System.out.println("How many eggs do you have?");
eggNumber = var1.nextInt();

while (while1){
if (eggNumber > 144){
eggsGross = eggNumber / 144;
eggsGrossRemainder = eggNumber % 144;

if(eggsGrossRemainder > 12) {
eggsDozen = eggsGrossRemainder / 12;
eggsDozenRemainder = eggsGrossRemainder % 12;
if (eggsDozenRemainder > 0){
eggsSingle = eggsDozenRemainder;
System.out.println("You have " + eggsGross + " gross amount of eggs, " + eggsDozen + " dozens mounts of eggs, and "
+ eggsSingle + " remainder eggs.");
while1 = false;
}
System.out.println("You have " + eggsGross + " gross amount of eggs and " + eggsDozen + " dozens mounts of eggs.");
while1 = false;
}
System.out.println("You have " + eggsGross + " gross amounts of eggs.");
while1 = false;
}
else if(eggNumber <= 144 && eggNumber >= 12){
eggsDozen = eggNumber / 12;
eggsDozenRemainder = eggNumber % 12;
if (eggsDozenRemainder > 0){
eggsSingle = eggsDozenRemainder;
System.out.println("You have " + eggsDozen + " dozen eggs and " + eggsSingle + " remainders.");
while1 = false;
}
System.out.println("You have " + eggsDozen + " dozen eggs.");
while1 = false;
}
else if (eggNumber > 0 && eggNumber < 12){
eggsSingle = eggNumber;
System.out.println("You have no Gross amounts or Dozen amounts, only " + eggsSingle + " singles.");
while1 = false;
}
else{
System.out.println("C'mon now... let's put a normal value in:");
}
}
}
}

最佳答案

将 boolean 值变为 false,意味着循环不会完成另一轮,但它将继续沿其路径前进,即“47”个鸡蛋>12且小于“144”,eggsDozenRemainder >0,因此 if block 将运行,但是后面的 block 也会运行,因为如果决策不是互斥的,请尝试 If (){}else{}

尝试控制流程图 http://en.wikipedia.org/wiki/Control_flow_diagram帮助理解。

关于java - True boolean while 语句在嵌套 if 中不退出循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19552191/

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