2015-11-04 20:10
JAVA自学笔记:不使用系统函数来计算日期处于当年的第多少天
前段时间练习了一个求闰年的功能,现在就可以用上啦,这次写一个不借助类库的时间函数,利用基础代码写一个计算求日期处于当年的第多少天的函数。
虽然也有简单的方法,例如直接定义每月的天数累加,然后加上当月的天数就可以算出当天处于当年的第多少天。但是这次咋们还是换种方法,虽然麻烦点,但好歹带点逻辑性。
首先我们需要一个数组,专门来存放指定年份的日历天数(必须自带闰年检测啦,不然二月份天数就不好算啦)。这里我们就新建一个函数好了,利用for循环和if判断,来按照月份的大小月规则来存放每月天数,然后让这个函数返回int数组值。
接下来就是输入输出啦,按照惯例,我们还是添加了输入格式检错的功能,月份肯定不会超过12或者小余1的吧,天数也不能超过当月的天数,不然要报错重新输入。
接下来直接利用for循环给总天数值days累加,例如7月8号,那么就是7月前(不包括7月)月份的所有天数,加上7月当月的day日期,即可得出总天数。
下面来看看代码吧:
import java.util.Scanner;
public class Test010 {
public static void main(String args[]){
Test010 t10=new Test010();
int days=0;
Scanner reader=new Scanner(System.in);
System.out.print("请输入年份:");
int year=reader.nextInt();
int[] monthA=t10.calendar(year);
System.out.print("请输入月份:");
int month=reader.nextInt();
System.out.print("请输入当月日期:");
int day=reader.nextInt();
while(true){
if(month>12||month<1){
System.out.print("月份格式错误,请重新输入:");
month=reader.nextInt();
continue;
}else if(day>monthA[month]||day<1){
System.out.print("日期范围错误,请重新输入:");
day=reader.nextInt();
continue;
}else{
break;
}
}
for(int i=1;i<month;i++){
days+=monthA[i];
}
days+=day;
System.out.printf("%d年%d月%d日是当年的第%d天",year,month,day,days);
}
public int[] calendar(int year){ //当年日历
int monthA[]=new int[13];
for(int i=1;i<monthA.length;i++){
if(i==1||i==3||i==5||i==7||i==8||i==10||i==12){
monthA[i]=31;
}else if(i==4||i==6||i==9||i==11){
monthA[i]=30;
}else{
if(year%4==0 && year%100!=0 || year%400==0){
monthA[i]=29;
}else{
monthA[i]=28;
}
}
}
return monthA;
}
}
标签:JAVA

