简体   繁体   中英

Why do I have to break; out of the loop here?

This is an algorithm to generate random numbers until a number for whom each digit is greater than the previous one. (Example: 1234, 1589 or 6789 NOT 1233 or 1334) Then, it prints all the generated numbers onto the console. I couldn't get it to display the numbers until I add the break; command in the if(), but why?

    public static void numeroNeuf() {

    boolean croissant = false;

    do {
        int entierAleatoire = rnd.nextInt(10000)+1;

        System.out.print(entierAleatoire + " ");

        while (entierAleatoire > 0) {
            int chiffre1 = entierAleatoire % 10;
            entierAleatoire /= 10;
            int chiffre2 = entierAleatoire % 10;

            if (chiffre2 > chiffre1 || chiffre2 == chiffre1) {
                croissant = false;
                break;
            } else {
                croissant = true;
            }
        }
    } while (croissant == false);
}

output :

1742 8912 1104 7216 7473 3276 3267 8780 7583 2143 8285 7555 6812 1893 2188 5351 5427 780 9211 2618 1605 3719 511 7671 5839 735 654 8075 7989 7702 891 4850 2891 3529 1420 642 2723 7217 1629 9742 9408 3910 2301 6936 3865 193 3221 6343 8505 8268 4489 3872 6643 5017 1367 

You are checking (or setting) the wrong value of croissant .

        if (chiffre2 > chiffre1 || chiffre2 == chiffre1) {
            croissant = false;
            break;
        } else {
            croissant = true;
        }
    }
} while (croissant == false);

You set it to false, then the while continues so long as the value is false.

If you set it to true instead then you will exit (and there is no need for the else clause at all as it must already be false).

There are several other strange things here though, for example you could just compare >= rather than both > and == .

There may well be other things as well, that's just what I saw on a quick glance through. I recommend using a debugger (whatever is built into your IDE) and step through the code as it executes one line at a time looking at what it is actually doing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM