vli*_*ina 0 java calendar for-loop
如何循环年份和月份以显示以下输出?显示期间的限制是当前月份和年份。此外,显示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
}
}
}
Run Code Online (Sandbox Code Playgroud)
}
预期产量:
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
尝试下面的代码。我正在使用Java 8和java.time.LocalDate,
LocalDate currentDate = LocalDate.now();
int year = currentDate.getYear();
int month = currentDate.getMonthValue();
for (int i = year - 2; i <= year; i++) {
for (int j = 1; j <= 12; j++) {
if (i == year && j == month) {
System.out.print(i + " " + j + " ");
break;
}
System.out.print(i + " " + j + " ");
}
}
}
Run Code Online (Sandbox Code Playgroud)
输出量
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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
118 次 |
| 最近记录: |