1

我是java新手,我正在尝试编写这个程序作为练习。程序采用当前时区偏移量并显示当前时间。但有些时候我的时间是负面的。我认为这里有一个逻辑错误,但我找不到它。

Enter the time zone offset to GMT: -4
The current time: -2:48:26

我正在使用纽约(格林威治标准时间 -4 小时)

// A program that display the current time, with the user input a offset

import java.util.Scanner;

class CurrentTime {
    public static void main(String[] args) {
        // Create a Scanner object
        Scanner input = new Scanner(System.in);
        long totalMillSeconds = System.currentTimeMillis();

        long totalSeconds = totalMillSeconds / 1000;
        long currentSecond = (int)totalSeconds % 60;

        long totalMinutes = totalSeconds / 60;
        long currentMinute = totalMinutes % 60;

        long totalHours = totalMinutes / 60;
        long currentHour = totalHours % 24;

        // Prompt user to ask what is the time zone offset
        System.out.print("Enter the time zone offset to GMT: ");
        long offset = input.nextLong();

        // Adjust the offset to the current hour
        currentHour = currentHour + offset;
        System.out.print("The current time: " + currentHour + ":" 
                + currentMinute + ":" + currentSecond);

    }
}
4

2 回答 2

4

我认为这里有一个逻辑错误,但我找不到它。

我认为逻辑错误是,当您向“小时”添加负偏移量时,您可能会在前一天得到一个小时。(还有一个相关的问题。如果偏移量足够大,你可能会在第二天结束一个小时;即一个大于 24 的“小时”值......通过你的方法。)

简单的修复是这样的:

currentHour = (currentHour + offset + 24) % 24;    // updated ...

如果您不知道 '%'(余数)运算符的作用,请阅读.

该页面没有提到(以及我忘记的)是余数的符号......如果它非零......与股息的符号相同。(见JLS 15.17.3)。所以我们需要24在取余数之前添加,以确保余数为正。

于 2013-06-29T02:53:29.587 回答
2

你的问题几乎在最后

currentHour = currentHour + offset;

想一想:如果当前时间是 1,时间偏移量是 -4,你会得到什么?

你可以这样做:

currentHour = (currentHour + offset + 24) % 24;
于 2013-06-29T02:52:14.933 回答