简体   繁体   English

在while循环中仅打印一次语句

[英]Printing a statement only once in a while loop

This is probably very simple, however I have completely blanked and would appreciate some pointers. 这可能很简单,但是我已经完全空白了,不胜感激。 I'm creating a small game we have been assigned where we select numbers and are then provided a target number to try and reach using the numbers we selected. 我正在创建一个小游戏,我们已经分配了一个数字,您可以在其中选择数字,然后提供一个目标数字,以尝试使用选择的数字达到目标。 Inside my while loop once my condition hits 6 it asks the user to generate the target number, however once they do it prints the same string again "Generate the final string" how do I print this only once? 在我的while循环内,一旦我的条件达到6,它会要求用户生成目标编号,但是一旦他们这样做,它就会再次打印相同的字符串“生成最终的字符串”,我该如何只打印一次?

Here is the code if it will help. 这是代码,如果有帮助的话。

while (lettersSelected == false) {

            if (finalNum.size() == 6) {
                System.out.println("3. Press 3 to generate target number!");

            } // Only want to print this part once so it does not appear again.


            Scanner input = new Scanner(System.in);

            choice = input.nextInt();

            switch (choice) {
            case 1:
                if (finalNum.size() != 6) {
                    largeNum = large.get(r.nextInt(large.size()));
                    finalNum.add(largeNum);
                    largeCount++;
                    System.out.println("Numbers board: " + finalNum + "\n");
                }

                break;

It can be done very easily. 这可以很容易地完成。

boolean isItPrinted = false;

while (lettersSelected == false) {

            if ((finalNum.size() == 6) && (isItPrinted == false)) {
                System.out.println("3. Press 3 to generate target number!");
                isItPrinted = true;
            }

The condition if (finalNum.size() == 6) is satisfied first and so the string is printed. 首先满足条件if (finalNum.size() == 6) ,因此将字符串打印出来。 However, during the next iteration of the while loop, the size of finalNum has not changed as the contrary of the condition is checked in the case 1 of the switch and the size is not changed anywhere between these two statements. 但是,在while循环的下一次迭代期间, finalNum的大小没有更改,因为在开关的case 1中检查了相反的条件,并且在这两个语句之间的任何位置都没有更改大小。

You can add a flag variable and set it to true , add a check for that variable in the if contidion and if the if-clause is entered, set the variable to false : 您可以添加一个标志变量并将其设置为true ,在if条件中添加对该变量的检查, if-clause输入了if-clause则将该变量设置为false

boolean flag = true;

while (lettersSelected == false) {

    if (finalNum.size() == 6 && flag) {
        System.out.println("3. Press 3 to generate target number!");
        flag = false;
    }

    // ...
}

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

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