Reputation: 79
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;
Upvotes: 1
Views: 18166
Reputation: 34146
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;
}
// ...
}
Upvotes: 0
Reputation: 4176
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.
Upvotes: 0
Reputation: 23029
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;
}
Upvotes: 1