简体   繁体   English

为什么我必须打破; 在这里跳出循环?

[英]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. (例如:1234、1589 或 6789 NOT 1233 或 1334)然后,它将所有生成的数字打印到控制台上。 I couldn't get it to display the numbers until I add the break;在添加中断之前,我无法让它显示数字; command in the if(), but why? if() 中的命令,但为什么呢?

    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 .您正在检查(或设置)错误的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.您将其设置为 false,那么只要值为 false,while 就会继续。

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).如果您将其设置为 true,那么您将退出(并且根本不需要 else 子句,因为它必须已经为 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.我建议使用调试器(无论您的 IDE 中内置什么)并逐步执行代码,因为它一次执行一行,查看它实际在做什么。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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