第二章节 题2.8
题目
题目描述
2.8(当前时间)程序清单2-7给出了显示当前格林尼治时间的程序。修改这个程序,提示用户输入相对于GMT的时区偏移量,然后显示在这个特定时区的时间。下面是一个运行示例:
Enter the time zone offset to GMT: -5 Enter
The current time is 4:50:34
解析
本题要求要有输入和输出。对于输入,我们需要先构造Scanner类对象,且要和标准输入流System.in关联,实现数据的输入,注意读取的数据类型应该采用哪种方法获取输入。
备注(2-7程序清单):
public class ShowCurrentTime {
public static void main(String[] args) {
// Obtain the total milliseconds since midnight, Jan 1, 1070
long totalMilliseconds = System.currentTimeMillis();
// Obtain the total seconds since midnight, Jan 1, 1070
long totalSeconds = totalMilliseconds / 1000;
// Compute the current second in the minute in the hour
long currentSecond = totalSeconds % 60;
// Obtain the total minutes
long totalMinutes = totalSeconds / 60;
// Compute the current minute in the hour
long currentMinute = totalMinutes % 60;
// Obtain the total hours
long totalHours = totalMinutes / 60;
// Compute the current hour
long currentHour = totalHours % 24;
// Display results
System.out.println("Current time is " + currentHour + ":" + currentMinute + ":" + currentSecond + " GMT");
}
}
代码
本题jdk1.8和jdk18代码通用
jdk1.8和jdk18代码示例
代码展示
import java.util.Scanner;
public class Test2_8 {
public static void main(String[] args) {
// Obtain the total milliseconds since midnight, Jan 1, 1070
long totalMilliseconds = System.currentTimeMillis();
// Obtain the total seconds since midnight, Jan 1, 1070
long totalSeconds = totalMilliseconds / 1000;
// Compute the current second in the minute in the hour
long currentSecond = totalSeconds % 60;
// Obtain the total minutes
long totalMinutes = totalSeconds / 60;
// Compute the current minute in the hour
long currentMinute = totalMinutes % 60;
// Obtain the total hours
long totalHours = totalMinutes / 60;
// Compute the current hour
long currentHour = totalHours % 24;
/** 修改 **/
System.out.print("Enter the time zone offset to GMT:");
Scanner input = new Scanner(System.in);
int offset = input.nextInt(); // 读取偏移量
currentHour = (currentHour + offset) % 24; // currentHour + offset如果小于0得到的结果会不正确,对24取余可以得到正确答案
/** 修改 **/
// Display results
System.out.println("Current time is " + currentHour + ":" + currentMinute + ":" + currentSecond + " GMT");
}
}
运行结果(以+8时区为例)
Enter the time zone offset to GMT:+8
Current time is 12:32:54 GMT