由于我的任务,我想知道如何做到这一点。
package leapyearsassignment;
import java.util.Scanner;
public class LeapYearsAssignment {
public static void main(String[] args) {
int leapyear;
int addyear = 4;
int year;
Scanner in = new Scanner(System.in);
System.out.println("Please enter a year to print the next 20 years.");
year = in.nextInt();
System.out.println( "You are asking for the leap years starting from " + year + ".");
//for loop here?
}
}
这就是我开始想知道如何能够放置一个' for循环'打印用户想要的下一个20年的闰年。
编辑:这是我之前制作的代码:
package leapyearsassignment;
public class LeapYearsAssignment {
public static void main(String[] args) {
int year;
for ( year = 2016; year <= 2092; year = year +4) {
System.out.println(year);}
}
}
但不是2016年,我想要用户想要的那一年。我对编程很新,几个月前刚刚开始;确切地说是9月。
答案 0 :(得分:1)
Scanner sc = new Scanner(System.in);
System.out.println("Enter the year to check for leap year.");
int year = sc.nextInt();
System.out.println("The next 20 leap years from the given year " + year+ " are: ");
int count =0;
while(count != 20){
year = year+4;
if((year%400==0) || (year%4==0 && year%100 != 0)){
System.out.println(year);
}
count++;
}
答案 1 :(得分:0)
这样做的一种方法(正确计算不规则的闰年)是:
要确定年份是否为闰年,您可以使用此方法:
public static boolean isLearYear(int year) {
return year % 4 == 0 & (year % 100 != 0 || year % 400 == 0);
}
(这会检查年份是否可被4整除,并说明每100年不闰年的特殊例外,但每400年再次是闰年。)
答案 2 :(得分:0)
Scanner in = new Scanner(System.in);
int count = 0;
System.out.println("Enter a year");
int current_year = in.nextInt();
System.out.println("The next 20 leap years from "+current_year+" are ");
while(count < 20){
if((current_year % 4 == 0) && (current_year % 100 != 0) || (current_year % 400 == 0))
{
System.out.print(current_year+", ");
count++;
}
current_year++;
}