我一直在尝试制作一个简单的程序,该程序将打印出两个输入年份之间的闰年。我已经制作了每年检查它是否是闰年然后打印它的循环,但我希望能够在每行上只显示 10 年,而不仅仅是在一条长线上显示所有这些年。
所以像这样:
1004, 1008, 1012, 1016, 1020, 1024, 1028, 1032, 1036, 1040,
1044, 1048, 1052, 1056, 1060, 1064, 1068, 1072, 1076, 1080,
1084, 1088, 1092, 1096, 1104, 1108, 1112, 1116, 1120, 1124,
1128, 1132, 1136, 1140, 1144, 1148, 1152, 1156, 1160, 1164,
1168, 1172, 1176, 1180, 1184, 1188, 1192, 1196, 1200.
而不是这个:
1004, 1008, 1012, 1016, 1020, 1024, 1028, 1032, 1036, 1040, 1044, 1048, 1052...
我尝试了各种不同的方法来实现这一点,嵌套 for 循环等,但目前我似乎无法实现它。抱歉,如果这是一个简单回答的愚蠢问题,我学习 Java 的时间并不长。
到目前为止,这是我的代码,它在一行上打印了所有年份:
import java.util.Scanner;
public class LeapYears {
public static void main(String[] args)
{
int firstY, finalY;
Scanner kb = new Scanner(System.in);
System.out.print("Enter start year: ");
firstY = kb.nextInt();
System.out.print("Enter end year: ");
finalY = kb.nextInt();
for(; firstY <= finalY; firstY++) {
if ((firstY % 4) == 0) {
if ((firstY % 100) == 0) {
if ((firstY % 400) == 0 ) {
System.out.print(firstY + ", ");
firstY++;
}
} else {
System.out.print(firstY + ", ");
}
}
}
}
}