计算用户输入的日期离1900年1月1日相距多少天
分析:
-
本题需要用到键盘输入:Scanner
-
注意平年闰年, 闰年分为普通闰年和世纪闰年。
i % 400 == 0 || (i % 4 == 0 && i % 100 != 0)
-
闰年二月份为29天,平年28天。
-
逐步计算:首先进行最简单的天数相差计算,然后看年份相差,最后看月份相差。
代码案例演示:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("请输入年份:");
int year = sc.nextInt();
System.out.println("请输入月份:");
int month = sc.nextInt();
System.out.println("请输入日期:");
int day = sc.nextInt();
//日期天数相差
int sumDay = day - 1;
//年份天数相差
for (int i = 1900; i < year; i++) {
if ((i % 400 == 0) || (i % 4 == 0 && i % 100 != 0)) {
sumDay += 366;
}else {
sumDay += 365;
}
}
//月份相差天数
for(int i = 1; i < month;i++){
switch (i){
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
sumDay += 31;
break;
case 2:
if ((year % 400 == 0) || (year % 4 == 0 && year % 100 != 0)){
sumDay += 29;
}else {
sumDay += 28;
}
break;
default:
sumDay += 30;
}
}
System.out.println("相距1900年1月1日:" + sumDay + "天。");
}
测试结果为:
打印如图三角形
方法一:
分析:
- 三角形行高为4,行号为 i ,每一行 * 的个数为
2*i-1
如:
第一行: 2 * 1 - 1 = 1个 *
第二行:2 * 2 - 1 = 3个 *
以此类推!
- 首先把三角形打印出来,注意换行问题:
int rowNum = 4;//行数
for (int i = 1; i <= rowNum; i++) {
for (int j = 0; j < 2 * i - 1; j++) {
System.out.print("*");
}
System.out.println();// * 打印之后换行
}
结果为:
这时候还需要再 * 前面加入 空格 才能实现题目要求的三角形:
假设总行数为: rowNum = 4
- 每一行的空格个数:
rowNum - i
如:
第一行空格数为: rowNum - 1 = 3
第二行空格数为: rowNum - 2 = 2
以此类推!
这时候尝试用键盘输入行高:rowNum,打印题目要求三角形
空格打印需要在 * 打印前进行!注意换行问题
实现代码如下:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("请输入三角形行高:");
int rowNum = sc.nextInt();
for (int i = 1; i <= rowNum; i++) {
for(int j = 0; j < rowNum - i;j++){
System.out.print(" ");
}
for(int j = 0 ;j < 2*i-1; j++){
System.out.print("*");
}
System.out.println();
}
}
测试结果为:
方法二:
打印如图三角形:
思路:可以把三角形拆分成三部分进行打印:
1.打印红色空白三角形
2.打印蓝色三角形
3.打印绿色三角形
代码演示:
public static void printTriangle(){
for (int i = 1; i <= 5; i++) {
for (int j = 5; j >= i; j--) {//红色空白三角形
System.out.print(" ");
}
for (int j = 1; j <= i; j++) {//蓝色三角形
System.out.print("*");
}
for (int j = 1; j < i; j++) {//绿色三角形
System.out.print("*");
}
System.out.println();
}
}
99乘法表打印
public class Print99 {
public static void main(String[] args) {
for (int i = 1; i <= 9; i++) {
for (int j = 1; j <= i; j++) {
System.out.print(j + "*" + i + "=" + j * i + " ");
}
System.out.println();
}
}
}
输出: