找到下一个闰年 Java

huangapple go评论73阅读模式
英文:

finding next leap year java

问题

代码在第一个年份是闰年的情况下是有效的,所以如果我说年份是2004,它会返回2008,但是当起始年份不是闰年时,它不会返回任何内容。如果,例如:给定的年份是2001、2002或2003,下一个闰年将是2004。我知道使用while循环是有道理的,但我不知道里面应该放什么。另外,我只能使用基本的Java格式,所以不能使用像java.time.Year这样的输入类。

public static boolean leapYear(int year) {
  boolean isLeap = true;
  if (year % 4 == 0) {
    if (year % 100 == 0) {
      if (year % 400 == 0)
        isLeap = true;
      else
        isLeap = false;
    } else
      isLeap = true;
  } else {
    isLeap = false;
  }
  return isLeap;
}

public static int nextLeapYear(int year) {
  int nextLeap = 0;

  if (leapYear(year)) {
    nextLeap = nextLeap + 4;
  } else {
    while (!leapYear(year + nextLeap + 1)) {
      nextLeap++;
    }
    nextLeap += 1;
  }
  year += nextLeap;
  return year;
}
英文:

The code works when the first year is a leap year so if I said the year was 2004 it would return 2008, but when the starting year is not a leap year, it returns nothing. How would I output that if, for ex: the given year was 2001, 2002, or 2003, the next leap year would be 2004. I know the while loop makes sense but I don't know what to put inside it. ALSO I can only use basic java formatting so no inputted classes like java.time.Year

public static boolean leapYear(int year) {
  boolean isLeap = true;
  if (year % 4 == 0) {
    if (year % 100 == 0) {
      if (year % 400 == 0)
        isLeap = true;
      else
        isLeap = false;
    } else
      isLeap = true;
  } else {
    isLeap = false;
  }
  return isLeap;
}

public static int nextLeapYear(int year) {
  int nextLeap = 0;

  if (leapYear(year)) {
    nextLeap = nextLeap + 4;
  } else {
    while (!leapYear(year)) {
      nextLeap++;
    }
    nextLeap += 1;
  }
  year += nextLeap;
  return year;
}

答案1

得分: 2

以下是翻译好的内容:

Granted this doesn't take much processing. But if you want to increase the efficiency of your program you might consider the following:

  • All leap years must be divisible by 4. But not all years divisible by 4 are leap years. So first, check for not divisible by 4. That will be 75% of the cases. In that event, return false.
   if (year % 4 != 0) {
        return false;
   }
  • As you continue, the year must be divisible by 4, so just make certain it is not a century year. This will be evaluated 25% of the time and will return true 24% of the time.
   if (year % 100 != 0) {
       return true;
   }
  • Lastly, the only category not checked are years divided by 400. If we got here in the logic, then it must be a century year. So return accordingly. This will evaluate to true 0.25% of the time.
  return year % 400 == 0;
英文:

Granted this doesn't take much processing. But if you want to increase the efficiency of your program you might consider the following:

  • All leap years must be divisible by 4. But not all years divisible by 4 are leap years. So first, check for not divisible by 4. That will be 75% of the cases. In that event, return false.
   if (year % 4 != 0) {
        return false;
   }
  • As you continue, the year must be divisible by 4 so just make certain it is not a century year. This will be evaluated 25% of the time and will return true 24% of the time.
   if (year % 100 != 0) {
       return true;
   }
  • lastly, the only category not checked are years divided by 400. If we got here in the logic, then it must be a century year. So return accordingly. This will evaluate to true .25% of the time.
  return year % 400 == 0;



</details>



# 答案2
**得分**: 0

你的代码有多处问题:

1. 你说:如果给定的年份是闰年,那么下一个闰年将会在4年后。**这是错误的**。如果传入的是1896年,你的算法会返回1900年,但是这是错误的;虽然1896年是闰年,但1900年却不是。

2. 如果你在`isLeapYear`代码中使用提前退出,代码会容易阅读得多。那个方法应该有很多return语句,缩减缩进。

3. 你的while循环会一遍又一遍地询问同样的问题,如果你对一个稳定的方法重复问同样的问题(而你的`isLeapYear`方法是稳定的),你会得到同样的答案,从而导致无限循环。你可能不想要`while(!leapYear(year))`,而是想要`while(!leapYear(year + nextLeap))`,并且在while循环之后不再额外增加`nextLeap`。

4. 实际上,你提到的这种情况:如果所述年份已经是一个闰年,添加4 - 根本不是必要的。仔细考虑一下:你可以直接删除那个if/else部分。你的代码将会变成`nextLeap`,那个while循环,和一个return语句。如果你写得正确,只需要3行代码。

<details>
<summary>英文:</summary>

Your code is broken in multiple ways:

1. You say: If the given year is a leap year, then the next leap year will be 4 years later. __This is false__. If you pass in 1896, your algorithm returns 1900, but this is wrong; whilst 1896 is a leap year, 1900 is not.

2. Your isLeapYear code would be miles easier to read if you early-exit. That method should have a lot of return statements and fall less indentation.

3. Your while loop will keep asking the same question over and over, and if you ask the same question to a stable method (and your isLeapYear method is stable), you get the same answer, resulting in an infinite loop. Presumably, you don&#39;t want `while(!leapYear(year))`, you want `while(!leapYear(year + nextLeap))`, and you don&#39;t want to increment nextLeap once more after the while loop.

4. in fact, your edge case of: If the stated year is already a year, add 4 - is not necessary at all. Think about it: You can just eliminate that if/else part. Your code will just be `nextLeap`, that while loop, and a return statement. a 3-liner, if you do right.


</details>



# 答案3
**得分**: 0

```java
EDIT: 我解决了,耶!

对于任何在处理这个问题上挣扎的人,以下是对我有效的方法 :)

    public static boolean leapYear(int year) {
        if(year % 4 == 0)
        {
            if( year % 100 == 0)
            {
                // 年份可被400整除,因此这一年是闰年
                if ( year % 400 == 0)
                    return true;
                else
                    return false;
            }
            else
                return true;
        }
        else
            return false;
		}
	


	public static int nextLeapYear (int year) {
		int nextLeap = 0;
		     while(leapYear(year + nextLeap) == false){
		    	 nextLeap++;
		    
		     }
			
			if(leapYear(year) == true)
				nextLeap += 4;
			
			year += nextLeap;
			return year;

		}
英文:

EDIT: I figured it out yay!

for anybody struggling w/ this, this is what worked for me 找到下一个闰年 Java

public static boolean leapYear(int year) {
    if(year % 4 == 0)
    {
        if( year % 100 == 0)
        {
            // year is divisible by 400, hence the year is a leap year
            if ( year % 400 == 0)
                return true;
            else
                return false;
        }
        else
            return true;
    }
    else
        return false;
	}



public static int nextLeapYear (int year) {
	int nextLeap = 0;
	     while(leapYear(year + nextLeap) == false){
	    	 nextLeap++;
	    
	     }
		
		if(leapYear(year) == true)
			nextLeap += 4;
		
		year += nextLeap;
		return year;

	}

答案4

得分: 0

> 每个能被4整除的年份都是闰年,但能被100整除且不能被400整除的世纪年份不是闰年。例如,1700年、1800年和1900年不是闰年,但1600年和2000年是闰年。
> - 美国海军天文台

你可以通过以下方式大大简化leapYear函数:

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

示例:

public class Main {
	public static void main(String[] args) {
		// 测试
		System.out.println(leapYear(1999));
		System.out.println(leapYear(2000));
		System.out.println(leapYear(1900));
		System.out.println(leapYear(1904));
	}

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

输出:

false
true
false
true

然后,你可以在nextLeapYear函数中使用它,如下所示:

public class Main {
	public static void main(String[] args) {
		// 测试
		System.out.println(nextLeapYear(1999));
		System.out.println(nextLeapYear(2000));
		System.out.println(nextLeapYear(2001));
	}

	public static int nextLeapYear(int year) {
		// 如果年份已经是闰年,返回 year + 4
		if (leapYear(year)) {
			return year + 4;
		}

		// 否则,通过逐一增加年份,直到找到闰年
		while (!leapYear(year)) {
			year++;
		}

		return year;
	}

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

输出:

2000
2004
2004

在生产代码中,你应该使用现成的类java.time.Year来处理年份。

import java.time.Year;

public class Main {
	public static void main(String[] args) {
		// 测试
		System.out.println(nextLeapYear(1999));
		System.out.println(nextLeapYear(2000));
		System.out.println(nextLeapYear(2001));
	}

	public static int nextLeapYear(int year) {
		Year yr = Year.of(year);
		// 如果年份已经是闰年,返回 year + 4
		if (yr.isLeap()) {
			return yr.plusYears(4).getValue();
		}

		// 否则,通过逐一增加年份,直到找到闰年
		while (!yr.isLeap()) {
			yr = yr.plusYears(1);
		}

		return yr.getValue();
	}
}

输出:

2000
2004
2004

了解更多关于现代日期时间 API 的内容,请参阅 教程:日期时间

英文:

> Every year that is exactly divisible by four is a leap year, except
> for years that are exactly divisible by 100, but these centurial years
> are leap years if they are exactly divisible by 400. For example, the
> years 1700, 1800, and 1900 are not leap years, but the years 1600 and
> 2000 are.
> - United States Naval Observatory

You can greatly simplify the function, leapYear as shown below:

public static boolean leapYear(int year) {
  return year % 400 == 0 || (year % 4 == 0 &amp;&amp; year % 100 != 0);
}

Demo:

public class Main {
	public static void main(String[] args) {
		// Test
		System.out.println(leapYear(1999));
		System.out.println(leapYear(2000));
		System.out.println(leapYear(1900));
		System.out.println(leapYear(1904));
	}

	public static boolean leapYear(int year) {
		return year % 400 == 0 || (year % 4 == 0 &amp;&amp; year % 100 != 0);
	}
}

Output:

false
true
false
true

Then, you can use it in the function, nextLeapYear as shown below:

public class Main {
	public static void main(String[] args) {
		// Test
		System.out.println(nextLeapYear(1999));
		System.out.println(nextLeapYear(2000));
		System.out.println(nextLeapYear(2001));
	}

	public static int nextLeapYear(int year) {
		// If year is already a leap year, return year + 4
		if (leapYear(year)) {
			return year + 4;
		}

		// Otherwise, keep incrementing year by one until you find a leap year
		while (!leapYear(year)) {
			year++;
		}

		return year;
	}

	public static boolean leapYear(int year) {
		return year % 400 == 0 || (year % 4 == 0 &amp;&amp; year % 100 != 0);
	}
}

Output:

2000
2004
2004

In production code, you should use the OOTB (Out-Of-The-Box) class, java.time.Year to deal with a year.

import java.time.Year;

public class Main {
	public static void main(String[] args) {
		// Test
		System.out.println(nextLeapYear(1999));
		System.out.println(nextLeapYear(2000));
		System.out.println(nextLeapYear(2001));
	}

	public static int nextLeapYear(int year) {
		Year yr = Year.of(year);
		// If year is already a leap year, return year + 4
		if (yr.isLeap()) {
			return yr.plusYears(4).getValue();
		}

		// Otherwise, keep incrementing year by one until you find a leap year
		while (!yr.isLeap()) {
			yr = yr.plusYears(1);
		}

		return yr.getValue();
	}
}

Output:

2000
2004
2004

Learn more about the modern date-time API at Trail: Date Time.

答案5

得分: 0

似乎要完全正确地获得 nextLeapYear() 并不容易。请允许我提出一种更简单的思路,我相信这样也会使编写代码更简单,或者修复可能存在的任何错误。

声明一个变量 candidateLeapYear,用来保存一个我们尚不知道是否会是 year 之后的下一个闰年的年份。将其初始化为 year + 1,因为我们知道下一个闰年的年份必须严格大于 year。在循环中,测试 candidateLeapYear 是否为闰年(使用另一种方法),只要它不是闰年,就将其增加 1。当循环终止时,candidateLeapYear 保存着下一个闰年的年份。将其返回。

英文:

It seems it not easy to get nextLeapYear() 100 % correct. Allow me to suggest a simpler way of thinking about it that will also — so I believe — make it simpler to code correctly and/or fix any bug there may be.

Declare a variable candidateLeapYear to hold a year that we don’t yet know whether will be the next leap year after year. Initialize it to year + 1 since we know that the next leap year will need to be strictly greater than year. In a loop test whether candidateLeapYear is a leap year (use the other method), and as long as it isn’t, increment by 1. When the loop terminates, candidateLeapYear holds the next leap year. Return it.

huangapple
  • 本文由 发表于 2020年10月14日 08:31:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/64344955.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定