第四章第十七题(一个月的天数)(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 -
参考代码:
package chapter04;
import java.util.Scanner;
public class Code_17 {
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();
}
}
- 结果显示:
Enter a year:1999
Enter a month:Feb
Feb 1999 has 28 days
Process finished with exit code 0