Java黑皮书课后题第3章:**3.21(科学:某天是星期几)泽勒一致性...编写程序,提示用户输入年、月、该月的哪一天,显示它是一周中的星期几
生活随笔
收集整理的這篇文章主要介紹了
Java黑皮书课后题第3章:**3.21(科学:某天是星期几)泽勒一致性...编写程序,提示用户输入年、月、该月的哪一天,显示它是一周中的星期几
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
**3.21(科學:某天是星期幾)澤勒一致性...編寫程序,提示用戶輸入年、月、該月的哪一天,顯示它是一周中的星期幾
- 題目
- 題目概述
- 運行示例
- 破題
- 代碼
題目
題目概述
**3.21(科學:某天是星期幾)澤勒一致性…編寫程序,提示用戶輸入年、月、該月的哪一天,顯示它是一周中的星期幾
澤勒一致性是由克里斯汀·澤勒開發的用于計算某天是星期幾的算法:
h = (q + (26 * (m + 1)) / 10 + k + k / 4 + j / 4 + 5 * j) % 7
其中:
- h是一個星期中的某一天(0為星期六;1為星期天;2為星期一;3為星期二;4為星期三;5為星期四;6為星期五)
- q是某月的第幾天
- m是月份(3為三月,4為四月,……,12為十二月),一月和二月分別記為上一年的13和14月
1月轉為13,2月轉為14,同時年份減1 - j是year / 100。
- k是該世紀的第幾年(即year%100)。
運行示例
Enter year: (e.g., 2012): 2015
Enter month: 1-12 : 1
Enter the day of the month:1-31 : 25
Day of the week is Sunday
Enter year: (e.g., 2012): 2012
Enter month: 5
Enter the day of the month:1-31 : 12
Day of the week is Saturday
破題
接收用戶輸入數據
轉換為公式規定要求
代入公式計算
得出結果并轉化為str
代碼
import java.util.Scanner;public class Test3_21 {public static void main(String[] args) {// 接收用戶數據Scanner input = new Scanner(System.in);System.out.println("Enter year: (e.g., 2012): ");int year = input.nextInt();System.out.println("Enter month: 1-12 : ");int m = input.nextInt(); // 需要調整System.out.println("Enter the day of the month:1-31 : ");int q = input.nextInt();// 完善變量的值if(m == 1 || m == 2){m += 12;year -= 1;}int k = year % 100;int j = year / 100;// 代入公式int h = (q + (26 * (m + 1)) / 10 + k + k / 4 + j / 4 + 5 * j) % 7;// 轉為對應的英文String str;switch (h){case 0:str = "Saturday";break;case 1:str = "Sunday";break;case 2:str = "Monday";break;case 3:str = "Tuesday";break;case 4:str = "Wednesday";break;case 5:str = "Thursday";break;default:str = "Friday";}System.out.println("Day of the week is " + str);} }總結
以上是生活随笔為你收集整理的Java黑皮书课后题第3章:**3.21(科学:某天是星期几)泽勒一致性...编写程序,提示用户输入年、月、该月的哪一天,显示它是一周中的星期几的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Java黑皮书课后题第3章:*3.20(
- 下一篇: Java黑皮书课后题第3章:**3.22