首页 技术 正文
技术 2022年11月9日
0 收藏 789 点赞 4,059 浏览 1372 个字

14 【程序 14 求日期】

题目:输入某年某月某日,判断这一天是这一年的第几天?

程序分析:以 3 月 5 日为例,应该先把前两个月的加起来,然后再加上 5 天即本年的第几天,特殊情况, 闰年且输入月份大于 3 时需考虑多加一天。

package cskaoyan;public class cskaoyan14 {
private static int year = 0;
private static int month = 0;
private static int day = 0;
private static int[] leapYear = { 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
private static int[] commonYear = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
private int sum = 0;@org.junit.Test
public void date() {
java.util.Scanner in = new java.util.Scanner(System.in);
year = in.nextInt();
month = in.nextInt();
day = in.nextInt();try {
if (verify(year, month, day)) {
if (leapYear(year)) {
for (int i = 0; i < month - 1; i++) {
sum += leapYear[i];
}
} else {
for (int i = 0; i < month - 1; i++) {
sum += commonYear[i];
}
}sum += day;System.out.println(year + "年" + month + "月" + day + "日" + "是这一年的第" + sum + "天");
}
} catch (Throwable e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
in.close();
}
}private static boolean verify(int yaer, int month, int day) throws Throwable {
if (year < 1) {
throw new Exception("YEAR ERROR");
}if (month < 1 || month > 12) {
throw new Exception("MONTH ERROR");
}if (day < 1 || day > 31) {
throw new Exception("DAY ERROR");
}if (month == 4 || month == 6 || month == 9 || month == 11) {
if (day > 30) {
throw new Exception("DAY ERROR");
}
}if (month == 2) {
if (leapYear(year)) {
if (day > 29) {
throw new Exception("DAY ERROR");
}
} else {
if (day > 28) {
throw new Exception("DAY ERROR");
}
}
}return true;
}private static boolean leapYear(int year) {
if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0 && year % 3200 != 0)) {
return true;
} else {
return false;
}
}
}
相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:8,954
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,479
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,291
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,108
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,740
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,774