삽질의 현장/- Java

[삽잡이::java] Java코드로 날짜를 랜덤하게 생성해보자!

shovelman 2016. 6. 8. 22:27



지난 시간에 이어 이번에는 

날짜를 랜덤하게 가져오는 장난질을 해보려고합니다.


날짜를 랜덤으로 생성하고자

삽질의 대가 무식한 삽잡이는 이와 같은 구상을 하였습니다.



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
public class RandomGame {
 
    private int iUserBirthMonth;
    private int iUserBirthDay;
    
    public int getUserBirthMonth()
    {
        return this.iUserBirthMonth;
    }
    public int getUserBirthDay()
    {
        return this.iUserBirthDay;
    }
 
    public void setCalendars()
    {       
        int iMinMonth = 1;
        int iMaxMonth = 12;
        int iMinDay = 1;
        int iMaxDay = 31;
        
        int iRandomMonth = (int)(Math.random() * iMaxMonth - iMinMonth + 1+ iMinMonth;
        int iRandomDay = 0;
        
        switch (iRandomMonth) {
        case 1:
        case 3:
        case 5:
        case 7:
        case 8:
        case 10:
        case 12:
            iRandomDay = (int) (Math.random() * iMaxDay - iMinDay + 1+ iMinDay; //최대 31일
            break;
        case 4:
        case 6:
        case 9:
        case 11:
            iRandomDay = (int) (Math.random() * (iMaxDay - 1- (iMinDay) + 1+ iMinDay; //최대 30일
            break;
        case 2:
            iRandomDay = (int) (Math.random() * (iMaxDay - 3- (iMinDay) + 1+ iMinDay; //최대 28일
            break;
        default:
            System.out.println("1~12 달 이외의 값이 들어옴");
        }
        
        this.iUserBirthMonth = iRandomMonth;
        this.iUserBirthDay = iRandomDay;
    }
}
 
cs



 뭐야!!! 개발 못하는거 티낼래!?


하하... 무식했습니다... 그렇습니다....

단순히 31일인 달, 30일인달 그리고 28일인 2월을 고려해서....

저렇게 더럽게.... 하하....


1
2
3
4
5
6
7
8
9
10
11
12
13
    public void setCalendars()
    {
        int[] maxDays = {312831303130313130313031};
        
        int iMinMonth = 1;
        int iMaxMonth = 12;
        
        int iRandomMonth = (int)(Math.random() * iMaxMonth - iMinMonth + 1+ iMinMonth;
        int iRandomDay = (int)(Math.random() * (maxDays[iRandomMonth-1-2+ 1);
        
        this.iUserBirthMonth = iRandomMonth;
        this.iUserBirthDay = iRandomDay;
    }
cs



그래서 이리 깔끔하게 바꿨습니다.


random() 메서드에 이어서 요란한 식이 있는 이유는 

바로 이 때문입니다!


1
2
3
4
5
    /*
     * 
     * Random한 값 범위를 설정하기 위한 로직
     * (int)(Math.random() * 최대값 - 최소값 + 1) + 최소값;
     */
cs


하하... 그리하여 저렇게 만들게 되었습니다.


switch - case문을 저리 더럽게 쓸 줄이야....

아직 한참 부족하군요.... 


아무튼... 이리하여~ 결과를 보면!?




이런식으로 랜덤하게 날짜를 생성할 수 있게 되었습니다!



굳~