Java开发:已知闰年,如何编写代码计算并输出下一个闰年?
Got it, let's get your code to find and output the next leap year exactly as you need. Here's a step-by-step breakdown of the changes you should make:
1. Extract Leap Year Logic into a Reusable Method
Your existing code already has the correct rules for checking leap years. Let's turn that logic into a static method—this way we can reuse it both for validating the input year and checking subsequent years, avoiding repeated code.
2. Add Logic to Locate the Next Leap Year
Once we confirm the input is a leap year, we'll start checking years starting from inputYear + 1 upwards. We'll loop through each year, using our reusable method to test if it's a leap year, until we find the first one that qualifies.
Modified Full Code
Here's the updated code with all necessary additions:
import java.util.Scanner; public class LabProgram { // Reusable method to check if a year is a leap year public static boolean isLeapYear(int year) { if (year % 4 == 0) { if (year % 100 == 0) { return year % 400 == 0; } else { return true; } } return false; } public static void main(String[] args) { Scanner scnr = new Scanner(System.in); int inputYear; int nextLeapYear; inputYear = scnr.nextInt(); // Check if input is a leap year if (isLeapYear(inputYear)) { System.out.println(inputYear + " is a leap year."); // Start checking from the year right after input nextLeapYear = inputYear + 1; // Loop until we find the next valid leap year while (!isLeapYear(nextLeapYear)) { nextLeapYear++; } // Output the required result format System.out.println(nextLeapYear + " is the leap year next to " + inputYear + "."); } else { System.out.println(inputYear + " is not a leap year."); // Optional: Add similar loop logic here if you want to find the next leap year for non-leap inputs } scnr.close(); } }
Key Details:
- Reusable
isLeapYearMethod: This method wraps the standard leap year rules (divisible by 4, but not by 100 unless also divisible by 400) so we can call it anytime we need to check a year's status. - Finding the Next Leap Year: We start at
inputYear + 1and increment the year until our method confirms it's a leap year—this guarantees we get the very next one. - Output Format: The final print statement matches exactly the structure you requested. For example, inputting 2016 will output
2020 is the leap year next to 2016.right after confirming 2016 is a leap year.
内容的提问来源于stack exchange,提问作者Erick Guerrero

