[英]Can I test for a condition inside a for-loop and if it is met, ignore a method call inside the loop?
我想在循環內調用方法,直到滿足條件(代表> = 1000),然后跳出循環並測試哪種方法更有效,然后跳回舊方法並忽略效率最低的方法調用。 這可能嗎? 這是我的示例代碼:
// Set the number of times each method is called
public void setReps(String target, String[] sa, long reps) {
shuffleArray(sa); // Shuffle the order of Strings in array
for (int i = 0; i < reps; i++) {
linearStringSearch(target, sa);
backwardLinearStringSearch(target, sa);
counter(); // counts winner
if (reps >= 1000)
chooseAlgorithm(target, sa);
}
因此,對於上面的代碼,我將測試linearStringSearch()和BackwardLinearStringSearch()以查看1000次循環后哪個效率更高,然后我想跳回去並根據結果忽略linearStringSearch()或BackwardLinearStringSearch()。 我可以在choiceAlgorithm()方法中編寫一個新循環,但如果可能的話,我希望跳回到舊循環。
無需使這個復雜化。
// Set the number of times each method is called
public void setReps(String target, String[] sa, long reps)
{
boolean ChosenFastest = false;
boolean ForwardsIsfaster = false;
shuffleArray(sa); // Shuffle the order of Strings in array
for (int i = 0; i < reps; i++)
{
if(ChosenFastest){
if(ForwardsIsFaster)
linearStringSearch(target, sa);
else
backwardLinearStringSearch(target, sa);
} else {
linearStringSearch(target, sa);
backwardLinearStringSearch(target, sa);
counter(); // counts winner
}
if (reps == 1000)
ChosenFastest = true;
if(ForwardsWasFastest()) //similar to choose algorithm
ForwardsIsfaster = true;
}
}
}
}
使用繼續; 循環內
例:
for (int x = 0; x > 10; x++) {
if(x > 4){
continue;
}
System.out.println("" + x);
}
由於繼續,輸出永遠不會達到5 ;
來源: Java Continue語句
為了回跳,您可以在循環內使用if語句,其中0 =未選擇算法,1 =線性,2 =向后線性。
for (int i = 0; i < reps; i++) {
if(chosenAlgo == 0) {
linearStringSearch(target, sa);
backwardLinearStringSearch(target, sa);
if(chosenAlgo == 1) {
linearStringSearch(target, sa);
}
else if(chosenAlgo == 2){
backwardLinearStringSearch(target, sa);
}
counter(); // counts winner
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.