Java 在 while 循环中只打印一次语句
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22508461/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Printing a statement only once in a while loop
提问by user3410327
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;
采纳答案by libik
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;
}
回答by anirudh
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.
if (finalNum.size() == 6)
首先满足条件,因此打印字符串。但是,在while
循环的下一次迭代期间,由于在 switch 中finalNum
检查了与条件相反的条件case 1
,并且在这两个语句之间的任何地方都没有更改大小,因此大小没有改变。
回答by Christian
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
输入了 ,则将该变量设置为false
:
boolean flag = true;
while (lettersSelected == false) {
if (finalNum.size() == 6 && flag) {
System.out.println("3. Press 3 to generate target number!");
flag = false;
}
// ...
}