您的位置:首页 > 其它

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

2017-03-14 08:53 716 查看
/*
2017年3月7日10:48:42
java基础50道经典练习题 例14
Athor: ZJY
Purpose:
1.能被4整除而不能被100整除.(如2004年就是闰年,1800年不是.)
2.能被400整除.(如2000年是闰年)
【程序14】
题目:输入某年某月某日,判断这一天是这一年的第几天?
程序分析:以3月5日为例,应该先把前两个月的加起来,
然后再加上5天即本年的第几天,特殊情况,闰年且输入
月份大于3时需考虑多加一天。

*/
import java.util.Scanner;

public class ProgramNo14_1
{
public static void main(String[] args)
{
System.out.print("请输入某年某月某日,以空格区分: ");
Scanner sc = new Scanner(System.in).useDelimiter("\\s");
int year = sc.nextInt();
int month = sc.nextInt();
int day = sc.nextInt();
sc.close();
System.out.print("输入的日期为:"+year+"年"+month+"月"+day+"日");
System.out.println("该日期是一年的第"+calculateDays(year, month, day)+"天!");
}
private static int calculateDays(int year, int month, int day)
{
if((12 < month)||(0 > month)||(31 < day)||(0 > day)){
System.out.print("输入数据无效!!");
System.exit(-1);
}
int days = 0;
byte[] byteArray = null;
byte[] byteArray1 = new byte[]{31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
byte[] byteArray2 = new byte[]{31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};

if((0 == year%400)||((0 == year%4)&&(0 != year%100))
byteArray = byteArray2;
else
byteArray = byteArray1;

if(byteArray[1] < day) {
System.out.print("输入数据无效!!");
System.exit(-1);
}

for (int i=0; i<month-1; i++) {
days += byteArray[i];
}
return (days + day);
}

}
/*
2017年3月7日10:48:42
java基础50道经典练习题 例14
Athor: ZJY
Purpose:
1.能被4整除而不能被100整除.(如2004年就是闰年,1800年不是.)
2.能被400整除.(如2000年是闰年)
*/

import java.util.Scanner;

public class ProgramNo14_2
{
public static void main(String[] args){
Scanner scan = new Scanner(System.in).useDelimiter("\\D");//匹配非数字
System.out.print("请输入当前日期(年-月-日):");
int year = scan.nextInt();
int month = scan.nextInt();
int date = scan.nextInt();
scan.close();
System.out.println("今天是"+year+"年的第"+analysis(year,month,date)+"天");
}
//判断天数
private static int analysis(int year, int month, int date){
int n = 0;
int[] month_date = new int[] {0,31,28,31,30,31,30,31,31,30,31,30};
if((year%400)==0 || ((year%4)==0)&&((year%100)!=0))
month_date[2] = 29;
for(int i=0; i<month; i++)
n += month_date[i];
return n+date;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐