2012-10-12 199 views
-2

我试图让方法LeapYear返回它是否或不是LeapYear(返回任何它是否实际上是语句)。基本上,我是新来的编码,我不知道如何返回一个字符串值,而不是一个int或一个双。任何人都可以帮助我吗?闰年方法

public static int LeapYear(int y) { 

    int theYear; 
    theYear = y; 

    if (theYear < 100) { 
     if (theYear > 40) { 
      theYear = theYear + 1900; 
     } else { 
      theYear = theYear + 2000; 
     } 
    } 

    if (theYear % 4 == 0) { 
     if (theYear % 100 != 0) { 
      System.out.println("IT IS A LEAP YEAR"); 
     } else if (theYear % 400 == 0) { 
      System.out.println("IT IS A LEAP YEAR"); 
     } else { 
      System.out.println("IT IS NOT A LEAP YEAR"); 
     } 
    } else { 
     System.out.println("IT IS NOT A LEAP YEAR"); 
    } 
} 
+3

帮助自己做读者的工作变得更轻松:去掉无关的代码(即因子和绝对值方法与您的问题无关:不要将它们包含在您的帖子中)。 – assylias

+0

当你关注闰年时,为什么张贴阶乘代码? –

回答

1
public static String LeapYear(int y) { 
int theYear; 
theYear = y; 
String LEAP_YEAR = "IT IS A LEAP YEAR"; 
String NOT_A_LEAP_YEAR = "IT IS NOT A LEAP YEAR"; 

if (theYear < 100) { 
    if (theYear > 40) { 
     theYear = theYear + 1900; 
    } else { 
     theYear = theYear + 2000; 
    } 
} 

if (theYear % 4 == 0) { 
    if (theYear % 100 != 0) { 
     //System.out.println("IT IS A LEAP YEAR"); 
     return LEAP_YEAR; 

    } else if (theYear % 400 == 0) { 
     //System.out.println("IT IS A LEAP YEAR"); 
     return LEAP_YEAR; 
    } else { 
     // System.out.println("IT IS NOT A LEAP YEAR"); 
     return NOT_A_LEAP_YEAR ; 
    } 
    } else { 
    //System.out.println("IT IS NOT A LEAP YEAR"); 
    return NOT_A_LEAP_YEAR ; 
    } 
return NOT_A_LEAP_YEAR ; 
} 
4

我不知道如何返回一个字符串值,而不是一个int或双。

你使返回类型的String

public static String leapYear(int y) 

,并返回一个字符串,而不是一个int

return "IT IS NOT A LEAP YEAR"; 
1

您可以使用方法:

static boolean isLeapYear(final int year) { 
    return year % 4 == 0 && (year % 100 != 0 || year % 400 == 0); 
} 

所以:

public static void LeapYear(int y) { 
    if (y % 4 == 0 && (y % 100 != 0 || y % 400 == 0)) { 
     System.out.println("IT IS A LEAP YEAR"); 
    } else { 
     System.out.println("IT IS NOT A LEAP YEAR"); 
    } 
}