2011-03-08 4 views
1
// Date3.java 
// Date3 class declaration. 

public class Date3 
{ 
    private int month; // 1-12 
    private int day; // 1-31 based on month 
    private int year; // any year 
    private String[] months = new String[]{ "january", "february", "march", "april", "may", "june", "july", "august", "september", "october", "november", "december" }; 


    // constructor: call checkMonth to confirm proper value for month; 
    // call checkDay to confirm proper value for day 
    public Date3(int theMonth, int theDay, int theYear) 
    { 
     month = checkMonth(theMonth); // validate month 
     year = theYear; // could validate year 
     day = checkDay(theDay); // validate day 

     System.out.printf( 
     "Date3 object constructor for date %s\n", this); 
    } // end Date3 constructor 

    public Date3(String m, int d, int y){ 
     this(m, d, y); 
    } 

    public Date3(int m, int y){ 
     this(m,0, y); 
    } 


    // utility method to confirm proper month value 
    private int checkMonth(int testMonth) 
    { 
     if (testMonth > 0 && testMonth <= 12) // validate month 
     return testMonth; 
     else // month is invalid 
     { 
     System.out.printf( 
      "Invalid month (%d) set to 1.", testMonth); 
     return 1; // maintain object in consistent state 
     } // end else 
    } // end method checkMonth 

    // utility method to confirm proper day value based on month and year 
    private int checkDay(int testDay) 
    { 
     int[] daysPerMonth = 
     { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; 

     // check if day in range for month 
     if (testDay > 0 && testDay <= daysPerMonth[ month ]) 
     return testDay; 

     // check for leap year 
     if (month == 2 && testDay == 29 && (year % 400 == 0 || 
      (year % 4 == 0 && year % 100 != 0))) 
     return testDay; 

     System.out.printf("Invalid day (%d) set to 1.", testDay); 
     return 1; // maintain object in consistent state 
    } // end method checkDay 

    public String getMonthString(int month){ 
     return months[month]; 
     } 


    /* public String monthAsString() 
    { 
     //returns month as a string rather than an integer 
     switch (month) 
     { 
      case 1: return "January"; 
      case 2: return "February"; 
      case 3: return "March"; 
      case 4: return "April"; 
      case 5: return "May"; 
      case 6: return "June"; 
      case 7: return "July"; 
      case 8: return "August"; 
      case 9: return "September"; 
      case 10: return "October"; 
      case 11: return "November"; 
      case 12: return "December"; 
      default: return "";   
     }   
    }*/ 




    // return a String of the form month/day/year 
    public String toString() 
    { 
     return String.format("%d/%d/%d", month, day, year); 
    } // end method toString 
} // end class Date3 





public class Date3Test { 

    /** 
    * @param args 
    */ 
    public static void main(String[] args) { 
     // TODO Auto-generated method stub 

     Date3 myDate = new Date3(9, 16, 2011); 
     Date3 myDate2 = new Date3("June", 24, 2010); 
     Date3 myDate3 = new Date3(259, 2005); 

     // all three dates above are equal and will therefore print 
     // the same dates 

     System.out.println(myDate); 
     System.out.println(myDate2); 
     System.out.println(myDate3); 

    } 

} 
+2

진지하게 시도해 보지 않으시겠습니까? – RAY

+0

나는 노력하고 있지만 나는 쌓여있다. – Mugetsu

+0

@Nishant 나는 넥타이 였기 때문에 대답을 찾지 못했습니다. – Mugetsu

답변

1

당신은 주어진 템플릿 초보자 문제가 될 수있는 이유를 이해 할 수를 한 손에 달 배열은 정적, 반면에 과부하가되지 않는다 생성자는 this (int, int, int) -constructor에 위임해야만 액세스 할 수 있습니다.

개월 배열 정적을 선언해야하는 코드를 수정하려면 월 문자열을 월 숫자로 변환하는 정적 메서드를 만듭니다. 또한 특정 줄을 주석 처리하여 을 컴파일하고 테스트해야합니다 (). 그래서

의 (Ⅱ) 함께

교체 해결하자

private String[] months 

로 :

private static String[] months 

교체 :

public Date3(String m, int d, int y){ 
    this(m, d, y); 
} 

로 :

public Date3(String m, int d, int y){ 
    this(convMonth(m), d, y); 
} 
public static int convMonth(String m) { 
    int index =1; // january will be 1 
    for(String month : months) { 
     if(m.equals(month)) break; 
     index++; 
    } 
    return index; 
} 

코멘트 아웃 번째 생성자 템플릿과 같이 :

/*public Date3(int m, int y){ 
    this(m,0, y); 
}*/ 

그리고 코멘트 아웃 Date3Test.java에서 그 두 번째 생성자 템플릿에 대한 호출 :

//System.out.println(myDate3); 

지금이 컴파일하고 실행하고 (ii)에 대한 anwer을 제공해야합니다. (iii) 해결할 수 있습니다. 주석 처리 된 두 번째 생성자 템플릿을 구현하고 해당 println()을 다시 활성화하면됩니다.

+0

감사합니다. 마지막 한장 알려 줄 수 있어요? – Mugetsu

+1

도움을 드리고 싶지만 (iii) 더 이상 볼 수 없습니다. –

+0

여기 있습니다 : iii) DDD YYYY – Mugetsu

0

좋아, 대한 (III) :

난 당신이 당신이 가진 것 때문에이 작업을 수행하기 위해, 자바 Date 클래스를 사용 할 수 없습니다 가정에 DDD를 변환하는 월, 일 - 중 - 한 달, 당신은 것입니다 그 특정 연도의 월 - 일 배열을 먼저 정의하는 것은 당연히 그 해의 2 월에 28 일 또는 29 일이 있는지 여부에 달려 있습니다.

INT [] = monthDays 새로운 INT [12] {} 31,28,31,3031303131303130,31

: 일반적인 경우에서는이있어 (400)에 의한 경우를 제외하고 100에 의해 사람을 제외하고 4로 나누어 년의 경우

, 당신은 28

좋아 29에, 당신의 DDD 당신 변환 할 수 있음을 변경해야합니다 (윤년에 대한 위키 피 디아 참조) 할 수있는 일 : 배열을 살펴보고 DDD가 현재 셀에 저장된 값보다 작을 때까지 현재 셀을 빼고 한 달 앞으로 이동했음을 기억하십시오. 예 : DDD = 41 -> 빼기 31 -> 날짜는 2 월 10 일입니다.