[英]What happens to a nested if statement in a for-loop if the conditions are not met and there is no else statement?
This is the code my prof gave on a practice exam. 这是我的教授在实践考试中给出的代码。 Since the first if statement has no else statement, does it exit the for-loop all together and move onto the next if statement?
由于第一个if语句没有else语句,它是否会同时退出for循环并移至下一个if语句? Then, if the second if-statement evaluates to true I'm assuming it's going to go through the first for-loop again and then the second.
然后,如果第二个if语句评估为true,则假定它将再次经历第一个for循环,然后再经历第二个。 Once it starts goes through the second for-loop again does the loop begin at j=1 again or another value?
一旦开始,它将再次通过第二个for循环,该循环会再次从j = 1或另一个值开始吗?
I'm also a little confused with what happens in the second if statement. 我对第二个if语句中发生的事情也有些困惑。 Does it mean the value at what the currentMaxIndex is becomes the s[i] value and then the currentMax value?
这是否意味着currentMaxIndex处的值变成s [i]值,然后成为currentMax值?
Thanks! 谢谢!
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;
}
If the condition isn't met the loop continues onto the next iteration, and the condition is tested again. 如果不满足条件,则循环继续进行下一次迭代,并再次测试条件。 That inner loop could also have been written like,
该内循环也可以这样写:
for (int j = 1; j <= i; j++) {
if (!cardLessThan(currentMax,s[j])){
continue;
}
currentMax = s[j];
currentMaxIndex = j;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.