0
点赞
收藏
分享

微信扫一扫

第四章第十七题(一个月的天数)(Days of a month)


*4.17(一个月的天数)编写一个程序,提示用户输入一个年份和一个月份名称的前三个字母(第一个字母使用大写形式),显示该月中的天数。如果输入的月份是非法的,显示一条出错信息。

下面是一个运行示例:
Enter a year: 2001
Enter a month: Jan
Jan 2001 has 31 days
Enter a year: 2016
Enter a month: jan
jan is not a correct month name

*4.17(Days of a month) Write a program that prompts the user to enter the year and the first three letters of a month name (with the first letter in uppercase) and displays the number of days in the month. If the input for month is incorrect, display a message as presented in the following sample runs:

Enter a year: 2001
Enter a month: Jan
Jan 2001 has 31 days
Enter a year: 2016
Enter a month: jan
jan is not a correct month name

下面是参考答案代码:

import java.util.*;

public class DaysOfMonthQuestion17 {
public static void main(String[] args) {
int year;
String month;

Scanner input = new Scanner(System.in);
System.out.print("Enter a year:");
year = input.nextInt();

System.out.print("Enter a month:");
month = input.next();

if ("Jan".equals(month))
System.out.println("Jan" + " " + year + " has 31 days");
else if ("Feb".equals(month))
{
if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0)
System.out.println("Feb" + " " + year + " has 29 days");
else
System.out.println("Feb" + " " + year + " has 28 days");
} else if ("Mar".equals(month))
System.out.println("Mar" + " " + year + " has 31 days");
else if ("Apr".equals(month))
System.out.println("Apr" + " " + year + " has 30 days");
else if ("May".equals(month))
System.out.println("May" + " " + year + " has 31 days");
else if ("Jun".equals(month))
System.out.println("Jun" + " " + year + " has 30 days");
else if ("Jul".equals(month))
System.out.println("Jul" + " " + year + " has 31 days");
else if ("Aug".equals(month))
System.out.println("Aug" + " " + year + " has 31 days");
else if ("Sep".equals(month))
System.out.println("Sep" + " " + year + " has 30 days");
else if ("Oct".equals(month))
System.out.println("Oct" + " " + year + " has 31 days");
else if ("Nov".equals(month))
System.out.println("Nov" + " " + year + " has 30 days");
else if ("Dec".equals(month))
System.out.println("Dec" + " " + year + " has 31 days");
else
System.out.println(month + " is not a correct month name");

input.close();
}
}

运行效果:

第四章第十七题(一个月的天数)(Days of a month)_代码规范


第四章第十七题(一个月的天数)(Days of a month)_System_02

注:编写程序要养成良好习惯
1.文件名要用英文,具体一点
2.注释要英文
3.变量命名要具体,不要抽象(如:a,b,c等等),形式要驼峰化
4.整体书写风格要统一(不要这里是驼峰,那里是下划线,这里的逻辑段落空三行,那里相同的逻辑段落空5行等等)
5.普通变量,方法名要小驼峰,类名要大驼峰,常量要使用全部大写加上下划线命名法
6.要学习相应的代码编辑器的一些常用快捷键,如:快速对齐等等


举报

相关推荐

第四章 第一个程序

第四章

第四章总结

第四章:表

第四章、数组

第四章:Hbase

0 条评论