简体   繁体   中英

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?

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. 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.

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 :

boolean flag = true;

while (lettersSelected == false) {

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

    // ...
}

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