1

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;
2
  • Can't you simply put it before the while, outside the cycle? Commented Mar 19, 2014 at 14:11
  • Maybe I'm misunderstanding something, but why don't you declare a boolean before the while with false value, check it in your if and set it to true when you entering the if statement? Commented Mar 19, 2014 at 14:12

3 Answers 3

1

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;
            }
Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

0

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;
    }

    // ...
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.