2013-06-29 1 views
1

저는 java를 처음 사용하기 때문에 연습으로이 프로그램을 작성하려고합니다. 프로그램은 현재 시간대 오프셋을 가져 와서 현재 시간을 표시합니다. 그러나 일부는 내 시간이 어떻게 부정적으로 나오는지 보여줍니다. 나는 여기에 논리 오류가 있다고 생각하지만 그것을 발견 할 수 없다.-4 오프셋 후 curren 시간이 음수입니다.

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

나는 뉴욕 (GMT -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

내가 거기 여기에 논리 오류가하지만 난 그것을 찾을 수 있다고 생각합니다.

"시간"에 음수 오프셋을 추가하면 논리 오류가 발생하여 전날의 1 시간으로 끝날 수 있다고 생각합니다. (그리고 관련 문제가 있습니다. 오프셋이 충분히 큰 경우 다음 번에 일, 즉 "시간"값이 24 이상일 수 있습니다.

당신은 '%'(나머지) 연산자가 무엇을하는지 알 수없는 경우

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

this 읽기 :

간단한 수정이됩니다.

그 페이지가 언급하지 않은 것 (그리고 내가 잊은 것)은 나머지의 부호 ... 0이 아닌 경우 ... 배당금의 부호와 같습니다. (JLS 15.17.3 참조). 따라서 나머지를 취하기 전에 24을 추가하여 양수 나머지를 확보해야합니다.

2

문제가 거의 끝이의

currentHour = currentHour + offset; 

생각에 일치한다 : 현재 시간 인 경우 1 시간 오프셋은 -4입니다. 당신은 무엇을 얻습니까?

당신이 할 수 있습니다 :

currentHour = (currentHour + offset + 24) % 24; 
관련 문제