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")); } } }
本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 无用评论 打赏 举报
悬赏问题
- ¥15 电脑和power bi环境都是英文如何将日期层次结构转换成英文
- ¥15 DruidDataSource一直closing
- ¥20 气象站点数据求取中~
- ¥15 如何获取APP内弹出的网址链接
- ¥15 wifi 图标不见了 不知道怎么办 上不了网 变成小地球了
- ¥50 STM32单片机传感器读取错误
- ¥50 power BI 从Mysql服务器导入数据,但连接进去后显示表无数据
- ¥15 (关键词-阻抗匹配,HFSS,RFID标签)
- ¥50 sft下载大文阻塞卡死
- ¥15 机器人轨迹规划相关问题