【发布时间】:2019-06-27 02:50:30
【问题描述】:
如何循环显示年份和月份以显示在输出下方? 显示时间限制为当前月份和年份 此外,显示 3 年,包括截至日期的年份。意思是如果现在是 2019 年,请显示 2018 年和 2017 年。
我尝试使用一些代码作为 java 应用程序运行,希望得到下面的预期输出,但这是我尝试并得到的。
如果有人能在这里阐明一些问题,将不胜感激。
public class TestClass {
public static void main(String[] args) {
Calendar today = Calendar.getInstance();
//month=5, index starts from 0
int month = today.get(Calendar.MONTH);
//year=2019
int year = today.get(Calendar.YEAR);
for(int i = 0; i < 3; i++) { //year
for(int j= 0; j <= month; j++) { //month
System.out.println("Value of year: " + (year - 2)); //start from 2017 and iterate to 2 years ahead
System.out.println("Value of month: " + (month + 1)); //start from January (index val: 1) and iterate to today's month
}
}
}
}
预期输出:
2017 1 2017 2 2017 3 2017 4 2017 5 2017 6 2017 7 2017 8 2017 9 2017 10 2017 11 2017 12
2018 1 2018 2 2018 3 2018 4 2018 5 2018 6 2018 7 2018 8 2018 9 2018 10 2018 11 2018 12
2019 1 2019 2 2019 3 2019 4 2019 5 2019 6
【问题讨论】:
-
我建议你不要使用
Calendar。该课程设计不良且早已过时。而是使用来自java.time, the modern Java date and time API 的YearMonth。如果在 Java 6 或 7 上,请通过 ThreeTen Backport 使用它。