例题分析:
1.要判断一个年份是否是闰年
(1)首先某个年份如果能被4整除同时还要被100整除或者能被400整除则为闰年
(2)然后我们可以用一个if函数就可以解决
import java.util.Scanner;
public class Demo18 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
//1.提示用户输入一个年份
System.out.print("Enter a year:");
int year = input.nextInt();
//2.判断其是否是闰年
if ((year % 4 == 0 && year % 100 !=0) || (year % 400 == 0)) {
System.out.println(year + "是闰年");
}
System.out.println("判断结束!");
}
}
2.
先找数字特点:
第4行 4 3 2 1 2 3 4
3 2 1 0 1 2 3
y = |x| + 1 x∈[-3,3]
第5行 5 4 3 2 1 2 3 4 5
4 3 2 1 0 1 2 3 4
y = |x| + 1 x∈[-4,4]
第i行 y = |x| + 1 x∈[-(i-1),i-1]
然后就可以用俩个for循环可以写出还需要一个for来控制
public class Demo41 {
public static void main(String[] args) {
for (int i = 1; i <= 7; i++) {
for (int k = 1; k <= 7 - i ;k++) {
System.out.print(" ");
}
for (int j = -(i - 1); j <= i - 1; j++) {
System.out.print(Math.abs(j) + 1 + " ");
}
System.out.println();
}
}
}