1)输入年份如2016;做合法性判断,如果输入不正确,重新输入,直到输入正确的年份
(2)接着输入月份如2;做合法性判断,如果输入不正确,重新输入,直到输入正确的月份
(3)打印出2016年是闰年,2月有29天
(4)重复的年份和月份的查询,提示用户是否继续查询,yes继续查询,no查询停止。
Java 循环结构 if else
- 写回答
- 好问题 0 提建议
- 关注问题
- 邀请回答
-
2条回答 默认 最新
isMae 2023-04-07 12:20关注参考下思路
import java.util.Scanner; public class LeapYearAndDaysInMonth { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); String input = "yes"; while (input.equals("yes")) { int year; do { System.out.print("请输入年份(如2016):"); while (!scanner.hasNextInt()) { System.out.print("输入不正确,请重新输入年份(如2016):"); scanner.next(); } year = scanner.nextInt(); } while (year <= 0); int month; do { System.out.print("请输入月份(1-12):"); while (!scanner.hasNextInt()) { System.out.print("输入不正确,请重新输入月份(1-12):"); scanner.next(); } month = scanner.nextInt(); } while (month < 1 || month > 12); boolean isLeapYear = false; if (year % 4 == 0) { if (year % 100 == 0) { if (year % 400 == 0) { isLeapYear = true; } } else { isLeapYear = true; } } int daysInMonth = 0; if (month == 2) { if (isLeapYear) { daysInMonth = 29; } else { daysInMonth = 28; } } else if (month == 4 || month == 6 || month == 9 || month == 11) { daysInMonth = 30; } else { daysInMonth = 31; } System.out.println(year + "年" + (isLeapYear ? "是" : "不是") + "闰年," + month + "月有" + daysInMonth + "天。"); do { System.out.print("是否继续查询?(yes或no)"); input = scanner.next().toLowerCase(); } while (!input.equals("yes") && !input.equals("no")); } } }本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 无用评论 打赏 举报