日期:2014-05-20  浏览次数:20567 次

新手请教,麻烦大神按照我的逻辑补全代码,某年某月某日是今年第多少天
我认为这段代码问题出在GetDaysOfOneYear,for循环条件不知道如何写,才能正确达成循环,如果还有别的问题,和逻辑问题,请大神指出,新手才学。

public class Work {

public static void main(String[] args) {

int year = 2012;
int mouth = 1;
int day = 10;
int days = GetDaysOfOneYear(2012, 2, 10);
System.out.println(days);

}

static int GetDaysOfOneYear(int year, int month, int day) {
int result = 0;
int[] ary = new int[] { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) {
ary[1] = 29;
for (int i = 0; i < ary.length; i++) {
result = result + ary[i];

}

} else {
for (int i = 0; i < ary.length; i++) {
result = result + ary[i];
}

}
return result;

}

}

------解决方案--------------------
你的这种做法虽然也可以做到,但是没有必要这样自己计算啊。应该按照月份循环,加上前面月份的天数,并加上日期。


        static int GetDaysOfOneYear(int year, int month, int day) {
int result = 0;
Calendar c = null;
c = Calendar.getInstance();
c.set(Calendar.YEAR, year);
c.set(Calendar.MONTH, month-1);
c.set(Calendar.DATE, day);
result = c.get(Calendar.DAY_OF_YEAR);
return result;

}


按照我的这种做法就简单多了,但是同样也可以做到。
------解决方案--------------------
水平一般般吧,称不上大神,参数传值,for语句调试,这些最好还是自己单步调试跟踪打印,有助于后面的深入。
基础知识没耐心教,做不了老师。