当我在一个循环中设置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:");
}
}
}
}
答案 0 :(得分:1)
将布尔值设置为false意味着循环不会完成另一个转弯,但是它将沿着它的路径继续,即“47”蛋是> 12且小于“144”,eggsDozenRemainder> 0,因此如果阻塞将运行,但是如果决定不相互排斥,那么随后的块将尝试If(){} else {}
尝试使用控制流程图http://en.wikipedia.org/wiki/Control_flow_diagram来帮助理解。