Java黑皮书课后题第3章:*3.30(当前时间)修改编程练习题2.8,以12小时时钟制显示小时数
生活随笔
收集整理的這篇文章主要介紹了
Java黑皮书课后题第3章:*3.30(当前时间)修改编程练习题2.8,以12小时时钟制显示小时数
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
*3.30(當前時間)修改編程練習題2.8,以12小時時鐘制顯示小時數
- 題目
- 題目概述
- 運行示例
- 編程練習題2.8
- 破題
- 代碼
題目
題目概述
*3.30(當前時間)修改編程練習題2.8,以12小時時鐘制顯示小時數
運行示例
Enter the time zone offset to GMT: -5
The current time is 4:50:34 AM
編程練習題2.8
歡迎點擊這里前往我的2.8博文,或復制url到瀏覽器:
https://blog.csdn.net/weixin_46356698/article/details/119783225
import java.util.Scanner;public class Test2_8 {public static void main(String[] args) {Scanner input = new Scanner(System.in);System.out.println("Enter the time zone offset to GMT:");int offset = input.nextInt();// Obtain the total milliseconds since midnight, Jan 1, 1970long totalMilliseconds = System.currentTimeMillis();// Obtain the total seconds since midnight, Jan 1, 1970long totalSeconds = totalMilliseconds / 1000;totalSeconds += offset * 60 * 60;// Compute the current second in the minute in the hourlong currentSecond = totalSeconds % 60;// Obtain the total minuteslong totalMinutes = totalSeconds / 60;// Compute the current minute in the hourlong currentMinute = totalMinutes % 60;// Obtain the total hourslong totalHours = totalMinutes / 60;// Compute the current hourlong currentHour = totalHours % 24;// Display resultsSystem.out.println("Current time is " + currentHour + ":"+ currentMinute + ":" + currentSecond + " GMT");} }破題
在理解2.8題目的基礎上只需要更改一小部分即可
我的理解,是在最后輸出前增加對小時的變換
對12求余即可獲取3.30要求的小時數
原數除12如果為0后面跟AM,如果為1后面跟PM
代碼
import java.util.Scanner;public class Test2_8 {public static void main(String[] args) {Scanner input = new Scanner(System.in);System.out.println("Enter the time zone offset to GMT:");int offset = input.nextInt();// Obtain the total milliseconds since midnight, Jan 1, 1970long totalMilliseconds = System.currentTimeMillis();// Obtain the total seconds since midnight, Jan 1, 1970long totalSeconds = totalMilliseconds / 1000;totalSeconds += offset * 60 * 60;// Compute the current second in the minute in the hourlong currentSecond = totalSeconds % 60;// Obtain the total minuteslong totalMinutes = totalSeconds / 60;// Compute the current minute in the hourlong currentMinute = totalMinutes % 60;// Obtain the total hourslong totalHours = totalMinutes / 60;// Compute the current hourlong currentHour = totalHours % 24;long currentHour_12 = currentHour % 12;// Display resultsif(currentHour / 12 == 0)System.out.println("Current time is " + currentHour_12 + ":"+ currentMinute + ":" + currentSecond + " AM");elseSystem.out.println("Current time is " + currentHour_12 + ":"+ currentMinute + ":" + currentSecond + " PM");} }總結
以上是生活随笔為你收集整理的Java黑皮书课后题第3章:*3.30(当前时间)修改编程练习题2.8,以12小时时钟制显示小时数的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Java黑皮书课后题第3章:**3.29
- 下一篇: Java黑皮书课后题第3章:*3.32(