0

while1 の値が true で、ループ条件が while(while1) であるループ内で while1 = false を設定すると、ループを終了する必要があります。ただし、ネストされた 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:");
            }
        }
    }
}
4

1 に答える 1

1

ブール値を false にすると、ループは次のターンを完了しませんが、パスに沿って継続します。つまり、「47」個の卵が 12 個以上で「144」個未満の場合、eggsDozenRemainder が >0 であるため、ブロックは実行されますが、決定が相互に排他的でない場合は、If (){}else{} を試してください。

制御フロー図http://en.wikipedia.org/wiki/Control_flow_diagramを試して理解を深めてください。

于 2013-10-23T21:20:39.683 に答える