![](/img/trans.png)
[英]Java : do While loop, all valid inputs accepted at the same time, only one should be
[英]execute an instruction only one time in a do while loop in java
在java中,我們如何在do while循環中只執行一次指令
do{
int param;
//execute this onty one time (depends of param)
//other instructions instructions
}while(condition)
謝謝你
將您想執行的語句只放入一次是一種方法,但是,當然,這假設語句出現在循環的末尾或開始處,並且不依賴於循環中發生的事情的條件循環(之前或之后)。 如果你有這樣的事情:
do {
// do some stuff
// one time condition
// do some more stuff
} while(condition);
您將無法輕松地將這些信息拉到循環之外。 如果這是您的問題,我的建議是在一次性語句周圍放置某種條件,並在語句運行時更新條件。 像這樣的東西:
boolean hasRun = false;
do {
// do some stuff
if(!hasRun) {
// one time condition
hasRun = true;
}
// do some more stuff
} while(condition);
怎么樣:
// one-time-code here
do
{
}
while ( condition );
將語句放在任何循環之外將導致它在每次調用該方法時只執行一次。
將您只想執行一次的語句移到 while 循環之外。
假設您想將代碼保留在循環內(其他海報提出了將代碼移到外部的明顯解決方案!),您可以考慮使用標志只執行一次:
boolean doneOnce=false;
do{
if (!doneOnce) {
\\execute this only one time
doneOnce=true;
}
\\other instructions instructions
} while (condition)
例如,如果您在循環中在一次性代碼之前有其他指令,則可能是一個有用的構造。
添加中斷:
do {
int param;
//execute this onty one time (depends of param)
//other instructions instructions
break;
} while(condition);
試圖准確回答你的問題:
bool ranOnce = false;
do{
int param;
if (param == SOMECONDITION and !ranOnce){
doWhatYouWant();
ranOnce = true;
}
//other instructions instructions
}while(condition)
所以你有它,根據 param只運行一次。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.