我似乎无法弄清楚这里出了什么问题。在第三种情况下 if (i == n && i % 2 == 0),我只希望它打印出 16 一次(如在 main 方法中给出的)。但出于某种奇怪的原因,它打印了 3 次。有人可以解释为什么吗???
public class Foursix {
public static void main(String[] args) {
printEven(1,7);
printEven(21,2);
printEven(16,16);
//main
}
public static void printEven(int i, int n) {
System.out.print("[ ");
//n is greater than i
if (i <= n) {
for (int t = i; t <= n; t++) {
if (t % 2 == 0) {
System.out.print(t + " ");
//if statement inner
}
//for loop
}
//if statement outer
}
//i is greater than n
if (i >= n) {
for (int t = i; t >= n; t--) {
if (t % 2 == 0) {
System.out.print(t + " ");
//if statement inner
}
//for loop
}
//if statement outer
}
//i is the same as n
if (i == n && i % 2 == 0) {
System.out.print(i);
//if statement
}
System.out.print("]");
System.out.println();
//printEven
}
//class
}