簡體   English   中英

我可以測試for循環內的條件嗎,如果滿足,請忽略循環內的方法調用?

[英]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()方法中編寫一個新循環,但如果可能的話,我希望跳回到舊循環。

一種方法是使用策略模式 您可以在接口中定義“ stringSearch”方法,使用線性和反向線性搜索實現該方法...然后編寫另一種實現,以測試(a),(b),然后選擇一個(可能通過存儲對“初始化”后的“正確”策略)。 您可能需要執行(a),(b)的幾次不同迭代,以解決任何“ JVM預熱 ”期間的問題。

UML策略模式

無需使這個復雜化。

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

一種方法是可以在Java中使用兩個for循環並使用帶有標簽的Continue語句。

因為標記的繼續語句會跳過標記有給定標簽的外部循環的當前迭代。

來源和參考- 繼續示例

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM