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");}
}


本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

相关文章

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部