【问题标题】:Need help understanding this and correctly interpreting it through my code?需要帮助理解这一点并通过我的代码正确解释它吗?
【发布时间】:2015-09-16 00:19:26
【问题描述】:

一个程序有一个方法,该方法将 int "Year" 作为参数,然后根据该参数确定它是否是闰年。他们给出了一个表格,显示哪个不是闰年,哪个是闰年

2010 /4 = 没有 .. /100 = 没有 .. /400 = 没有 .. 飞跃 = 没有

2012 /4 = 是 .. /100 = 否 .. /400 = 否 .. 飞跃 = 是

1900 /4 = 是 .. /100 = 是 .. /400 = 否 .. 跳跃 = 否

2000 /4 = 是 .. /100 = 是 .. /400 = 是 .. 跳跃 = 是

他们还希望该方法能够识别一年是否在公历 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 ");

    }
  }
}

【问题讨论】:

  • 您的代码比需要的更复杂:如果年份不能被 4 整除,则绝对不是闰年,因此在这种情况下,您无需同时测试可被 100 或 400 整除.如果它 is 可以被 4 整除,那么它就是闰年,除非它可以被 100 而不是 400 整除。为什么要使用“javascript”标签? Javascript != Java。
  • else 语句是怎么回事?这不是 else if 的工作原理......请阅读 else if docs.oracle.com/javase/tutorial/java/nutsandbolts/if.html

标签: java if-statement boolean boolean-expression


【解决方案1】:

你重复了很多代码;尝试使用比较器恢复它。

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 ");    
 }

【讨论】:

  • 感谢大家的帮助,肯定需要阅读更多关于这些内容的信息,但我们非常感谢您的帮助。干杯
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-07-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多