如果条件不满足且没有else语句,for循环中的嵌套if语句会发生什么?

时间:2014-12-10 01:08:30

标签: java arrays sorting for-loop nested

这是我的教授在练习考试中给出的代码。由于第一个if语句没有else语句,它是否一起退出for-loop并转移到下一个if语句?然后,如果第二个if语句的计算结果为true,我假设它将再次通过第一个for循环,然后是第二个。一旦它开始再次通过第二个for循环,循环再次从j = 1开始或另一个值?

我也对第二个if语句中发生的事情感到困惑。它是指currentMaxIndex变为s [i]值然后是currentMax值的值吗?

谢谢!

public class Cards {
  public static String[] sortCards(String[] s){ // SELECT SORT
     for (int i = s.length - 1; i >= 1; i--){
         // Find the maximum in the list[0..i]
         String currentMax = s[0];
         int currentMaxIndex = 0;
         for (int j = 1; j <= i; j++) {
             if (cardLessThan(currentMax,s[j])){
                 currentMax = s[j];
                 currentMaxIndex = j;
             }
         }
         // Swap list[i] with s[currentMaxIndex] if necessary;
         if (currentMaxIndex != i) {
             s[currentMaxIndex] = s[i];
             s[i] = currentMax;
          }
     }  
     return s;
    }
 static boolean cardLessThan(String s1, String s2){
     char s1s = s1.charAt(s1.length()-1); //suites
     char s2s = s2.charAt(s2.length()-1);
     if(s1s < s2s)
         return true;
     else if(s1s > s2s)
         return false;
     // Same suite cards - order determined by card number
     String n1 = s1.substring(0,s1.length()-1);
     String n2 = s2.substring(0,s2.length()-1);
     if(n1.equals("A") && !n2.equals("A")) return true;
     if(n1.equals("2") && !n2.equals("A") && !n2.equals("2")) return true;
     …
     return false;
    }

1 个答案:

答案 0 :(得分:0)

如果不满足条件,则循环继续到下一次迭代,并再次测试条件。内部循环也可以写成,

for (int j = 1; j <= i; j++) {
    if (!cardLessThan(currentMax,s[j])){
        continue;
    }
    currentMax = s[j];
    currentMaxIndex = j;
}