程序,该程序有一个方法,该方法以int "Year"作为参数,然后根据参数计算出它是否是闰年。他们给出了一个表格,显示哪些不是闰年,哪些是闰年
2010/4 = no . 1/100 = no ../400 = no ..Leap = no
2012/4 = yes ../100 = no ../400 = no ..Leap = yes
1900/4 = yes ../100 = yes ../400 = no ..Leap = no
2000/4 = yes ../100 = yes ../400 = yes ..Leap = yes
他们还希望该方法确定某一年是否在公历1565年之前
下面是我目前完成的代码。它在某些年份有效,但在另一些年份无效。很明显我做错了什么。如果有人能告诉我我做对了什么,我做错了什么,或者如何最好地去做这件事,我将不胜感激。
public class theleapyear{
public static void main( String [] args){
leapyear(2010);
leapyear(2012);
leapyear(1900);
leapyear(2000);
leapyear(1565);
}
public static void leapyear( int year){
if (year < 1565)
System.out.println( year + ":" + " predates the Gregorian Calendar ");
else
if (year % 4 != 0)
if (year % 100 != 0)
if (year % 400 != 0)
{
System.out.println( year + ":" + " is not a leap year ");
}
else
{
if (year % 4 == 0)
if (year % 100 != 0)
if (year % 400 != 0)
System.out.println( year + ":" + " is a leap year ");
}
else
{
if (year % 4 == 0)
if (year % 100 == 0)
if (year % 400 != 0)
System.out.println( year + ":" + " is not a leap year ");
}
else
{
if (year % 4 == 0)
if (year % 100 == 0)
if (year % 400 == 0)
System.out.println( year + ":" + " is a leap year ");
}
}
}
你重复了很多代码;尝试使用比较器恢复它。
public class theleapyear{
public static void main( String [] args){
leapyear(2010);
leapyear(2012);
leapyear(1900);
leapyear(2000);
leapyear(1565);
}
public static void leapyear( int year){
if (year < 1565)
System.out.println( year + ":" + " predates the Gregorian Calendar ");
else
{
if ((year%4 != 0){
System.out.println(year + ":" + " is not a leap year ");
}
else {
if((year%100==0 && year%400==0)||(year%100!=0 && year%400!=0){
System.out.println(year + ":" + " it is a leap year ");
}
else {
System.out.println(year + ":" + " is not a leap year ");
}