编写一个程序,从键盘上输入年、月、日数字,请判断并输出这个日期是今年的第几天。
时间: 2024-06-13 18:04:33 浏览: 80
这个程序可以使用switch-case结构或者if-else结构来实现。下面是使用switch-case结构的代码示例:
```
import java.util.Scanner;
public class DayOfYear {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("请输入year:");
int year = scan.nextInt();
System.out.println("请输入month:");
int month = scan.nextInt();
System.out.println("请输入day:");
int day = scan.nextInt();
int sumdays = 0;
switch (month) {
case 12:
sumdays += 30;
case 11:
sumdays += 31;
case 10:
sumdays += 30;
case 9:
sumdays += 31;
case 8:
sumdays += 31;
case 7:
sumdays += 30;
case 6:
sumdays += 31;
case 5:
sumdays += 30;
case 4:
sumdays += 31;
case 3:
if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) {
sumdays += 29;
} else {
sumdays += 28;
}
case 2:
sumdays += 31;
case 1:
sumdays += day;
}
System.out.println(year + "年" + month + "月" + day + "日是当年的第" + sumdays + "天");
}
}
```
使用if-else结构的代码示例:
```
import java.util.Scanner;
public class DayOfYear {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("请输入year:");
int year = scan.nextInt();
System.out.println("请输入month:");
int month = scan.nextInt();
System.out.println("请输入day:"); int day = scan.nextInt();
int sumdays = 0;
for (int i = 1; i < month; i++) {
switch (i) {
case 12:
case 10:
case 8:
case 7:
case 5:
case 3:
sumdays += 31;
break;
case 11:
case 9:
case 6:
case 4:
sumdays += 30;
break;
case 2:
if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) {
sumdays += 29;
} else {
sumdays += 28;
}
break;
}
}
sumdays += day;
System.out.println(year + "年" + month + "月" + day + "日是当年的第" + sumdays + "天");
}
}
```
阅读全文