Java黑皮书课后题第4章:*4.17(一个月的天数)编写一个程序,提示用户输入一个年份和一个月份名称的前3个字母(第一个字母使用大写形式),显示该月中的天数。如果月份非法则显示出错信息
生活随笔
收集整理的這篇文章主要介紹了
Java黑皮书课后题第4章:*4.17(一个月的天数)编写一个程序,提示用户输入一个年份和一个月份名称的前3个字母(第一个字母使用大写形式),显示该月中的天数。如果月份非法则显示出错信息
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
*4.17(一個月的天數)編寫一個程序,提示用戶輸入一個年份和一個月份名稱的前3個字母(第一個字母使用大寫形式),顯示該月中的天數。如果月份非法則顯示出錯信息
- 題目
- 題目概述
- 破題
- 運行示例
- 代碼
題目
題目概述
*4.17(一個月的天數)編寫一個程序,提示用戶輸入一個年份和一個月份名稱的前3個字母(第一個字母使用大寫形式),顯示該月中的天數。如果月份非法則顯示出錯信息
本題強推自己先做一遍,雖然題頭非常少,但綜合性非常強
破題
運行示例
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.Scanner;public class Test4_17 {public static void main(String[] args) {// 獲取用戶輸入的年份、月份(前int類型后String類型)Scanner input = new Scanner(System.in);System.out.println("Enter a year: ");int yearInput = input.nextInt();System.out.println("Enter a month: ");String monthInput = input.next();// 判斷月份的String類型長度是否為3,如果不是則返回出錯信息并強制退出程序int monthLenght = monthInput.length();if(monthLenght != 3){System.out.println(monthInput + " is not a correct month name");System.exit(1);}// 提取月份的第一個字符,賦值給char類型char monthFirstChar = monthInput.charAt(0);// 再轉為int型,判斷是否在'A'~'Z'(即[65, 90])范圍內int i = (int) monthFirstChar;if(i > 90 || i < 65){System.out.println(monthInput + " is not a correct month name");System.exit(1);}// 月份名稱轉為對應數字(這里最好用if..else..)int monthDigit = 0;if(monthInput.equals("Jan"))monthDigit = 1;else if(monthInput.equals("Feb"))monthDigit = 2;else if(monthInput.equals("Mar"))monthDigit = 3;else if(monthInput.equals("Apr"))monthDigit = 4;else if(monthInput.equals("May"))monthDigit = 5;else if(monthInput.equals("Jun"))monthDigit = 6;else if(monthInput.equals("Jul"))monthDigit = 7;else if(monthInput.equals("Aug"))monthDigit = 8;else if(monthInput.equals("Sep"))monthDigit = 9;else if(monthInput.equals("Nov"))monthDigit = 10;else if(monthInput.equals("Oct"))monthDigit = 11;else if(monthInput.equals("Dec"))monthDigit = 12;else{System.out.println(monthInput + " is not a correct month name");System.exit(1);}// 判斷指定年份是否為閏年:打標記錄boolean bool = false;if( ( (yearInput % 4 == 0) && (yearInput % 100 != 0) ) || (yearInput % 400 == 0) ){bool = true;}// 忽略閏年影響,單純判斷月份天數(28天、30天、31天)int monthDay = 0;switch (monthDigit){case 2: monthDay = 28;break;case 4: case 6: case 9: case 11:monthDay = 30;break;default:monthDay = 31;}// 如果是閏年且是2月,則月份天數+1if( (bool == true) && (monthDay == 28) ){monthDay += 1;}// 輸出結果System.out.println(monthInput + " " + yearInput + " has " + monthDay + " days");} }總結
以上是生活随笔為你收集整理的Java黑皮书课后题第4章:*4.17(一个月的天数)编写一个程序,提示用户输入一个年份和一个月份名称的前3个字母(第一个字母使用大写形式),显示该月中的天数。如果月份非法则显示出错信息的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Java黑皮书课后题第4章:4.16(随
- 下一篇: Java黑皮书课后题第4章:*4.18(