티스토리 뷰

Programming/JAVA

Java Web#18 자바 API (2)

copotter 2019. 3. 26. 20:31

day18 190315(2)


각종 API에 대해 배웠습니다. 소스에 있는 주석설명을 참조하시면 되겠습니다.


< Random >

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
package demo4;
 
import java.util.Random;
 
public class RandomDemo {
 
    public static void main(String[] args) {
        
        // 난수를 발생시키는 Random객체 생성
        Random random = new Random();
        
        // int범위의 최소값과 최대값 사이의 임의의 정수를 제공
        int num1 = random.nextInt();
        System.out.println(num1);
        
        // int nextInt(int max) : 0 <= 난수 < max 범위의 임의의 정수를 제공
        int num2 = random.nextInt(100);
        System.out.println(num2);
        
        // 1~6 사이값 임의의 정수 뽑는 방식
        int num3 = random.nextInt(6)+1;
        System.out.println(num3);
    }
}
cs

>> 앞 시간에 과제(Lotto)를 할때 사용된 API입니다.

20, 21행에서와 같이 범위를 설정할때 random.nextInt(6)으로 0 <= 난수 < 6 설정을 한뒤 +1을 하면, 1<= 난수 < 7이되는 방식으로 하게 되겠습니다.


< Arrays >

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
package demo4;
 
import java.util.Arrays;
 
public class ArraysDemo {
 
    public static void main(String[] args) {
        
        int[] scores = {10301731465};
        Arrays.sort(scores);
        
        System.out.println(Arrays.toString(scores));
        
        String[] names = {"홍길동""이순신""강감찬""김유신""유관순""김구"};
        System.out.println(Arrays.toString(names));
    }
}
cs



< Date >

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
package demo4;
 
import java.util.Date;
import java.text.SimpleDateFormat;
 
public class DateDemo {
 
    public static void main(String[] args) {
        
        // 컴퓨터의 현재 날짜 및 시간정보를 갖고 있는 Date객체가 생성된다.
        Date now = new Date();
        System.out.println(now.toString());    // Date의 toString()은 날짜와 시간정보를 문자열로 제공하도록 재정의되어 있다.
        
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy년mm월dd일 hh시mm분ss초");
        String strNow = sdf.format(now);
        System.out.println(strNow);
        
        long value = now.getTime();            // System.currentTimeInMillis()와 동일한 값을 제공한다.
        System.out.println(value);
        
        now.setTime(1000000000000L);
        System.out.println(now);
    }
}
cs

>> 시간 정보 제공을 할때 자주 사용되는 API입니다.

14행처럼 SimpleDateFormat을 이용해서 표현 형식을 설정할 수 있습니다.



< Math >

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
package demo4;
 
public class MathDemo {
 
    public static void main(String[] args) {
        
        double result1 = Math.ceil(3.1);
        double result2 = Math.ceil(4.0);
        double result3 = Math.ceil(3.9);
        System.out.println(result1);
        System.out.println(result2);
        System.out.println(result3);
        System.out.println();
        
        double result4 = Math.floor(3.1);
        double result5 = Math.floor(3.0);
        double result6 = Math.floor(3.9);
        System.out.println(result4);
        System.out.println(result5);
        System.out.println(result6);
        System.out.println();
        
        double result7 = Math.round(3.1);        // 반올림
        double result8 = Math.round(4.0);
        double result9 = Math.round(3.9);
        System.out.println(result7);
        System.out.println(result8);
        System.out.println(result9);
    }
}
cs

>> 실행결과를 보면, 

4.0                왼쪽과 같이 출력된다.

4.0                ceil은 올림

4.0


3.0                floor은 내림

3.0

3.0


3.0                round는 반올림

4.0                이라는 원리로 보면 되겠습니다.

4.0



< System >

: 시스템의 각종 정보를 제공하는 API입니다.

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
package demo4;
 
public class SystemDemo {
 
    public static void main(String[] args) {
        
        // 시스템의 현재 시간정보 조회하기(밀리초 단위)
        // long System.currentTimeMillis()
        long time = System.currentTimeMillis();
        System.out.println(time);
        
        // 시스템의 속성값 조회하기
        // String System.getProperty(String name)
        String value1 = System.getProperty("java.version");
        String value2 = System.getProperty("os.name");
        String value3 = System.getProperty("user.name");
        String value4 = System.getProperty("user.home");
        System.out.println("자바버전 : " + value1);
        System.out.println("운영체제이름 : " + value2);
        System.out.println("사용자 이름 : " + value3);
        System.out.println("사용자 홈 디렉토리 : " + value4);
        
        // 시스템의 환경변수값 조회
        // String System.getenv(String name)
        String env1 = System.getenv("JAVA_HOME");
        String env2 = System.getenv("PATH");
        System.out.println("자바홈: " + env1);
        System.out.println("패스: " + env2);
    }
}
cs


< 박싱(오토 박싱) >

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
package demo4;
 
public class WrapperDemo1 {
 
    public static void main(String[] args) {
        Integer num1 = new Integer(30);                    // 박싱(Boxing)
        Integer num2 = new Integer("30");                // 박싱
        
        // 정수값 획득 : int intvalue()
        int value1 = num1.intValue();                    // 언박싱(Unboxing)
        int value2 = num2.intValue();
        System.out.println(value1);
        System.out.println(value2);
        
        
        Double num3 = new Double(3.14);                    // 박싱
        Double num4 = new Double("3.14");                // 박싱
        
        // 실수값 획득 : double doubleValue()
        double value3 = num3.doubleValue();                // 언박싱
        double value4 = num4.doubleValue();                // 언박싱
        System.out.println(value3);
        System.out.println(value4);
 
        Integer num1 = 10;        // 컴파일된 실행파일 : Integer num1 = new Integer(10);
        Double num2 = 3.14;        // 컴파일된 실행파일 : Double num2 = new Double(3.14);
        
        Integer num3 = new Integer(100);
        Double num4 = new Double(2.4);
        // 오토언박싱
        int value3 = num3;        // 컴파일된 실행파일 : int value3 = num3.intValue();
        double value4 = num4;    // 컴파일된 실행파일 : double value4 = num4.DoubleValue();
        
        System.out.println(num1);
        System.out.println(num2);
        System.out.println(value3);
        System.out.println(value4);
    }
}
 
 
cs

>> 해당 타입에 맞게 형변환을 해주는 것을 박싱이라고 한다. 25,26행과 같이 오토 박싱이 가능하고, 실행파일에는 주석과 같이 저장된다.


< Calendar >

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
package demo5;
 
import java.util.Calendar;
 
public class CalendarDemo {
 
   public static void main(String[] args) {//GregorianCalendar 구현해놓은 캘린더 객체
      Calendar cal = Calendar.getInstance();
      System.out.println(cal);
      
      int year = cal.get(Calendar.YEAR);
      int month =cal.get(Calendar.MONTH);
      int day = cal.get(Calendar.DAY_OF_MONTH);
      int hour = cal.get(Calendar.HOUR);
      int minute = cal.get(Calendar.MINUTE);
      int second = cal.get(Calendar.SECOND);
      
      System.out.println("년 : " + year);   // 월은 0 부터 시작이라서 2로 표시된다.
      System.out.println("월 : " + month);
      System.out.println("일 : " + day);
      System.out.println("시 : " + hour);
      System.out.println("분 : " + minute);
      System.out.println("초 : " + second);
        
   }
}
 
cs



< Parser >
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
package demo5;
 
 
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
 
public class ParserDemo1 {
 
    public static void main(String[] args) throws ParseException {
        
        // 오늘
        Date now = new Date();
        
        String text = "1995.11.02";
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd");
        // 결혼한 날
        Date weddingDay = sdf.parse(text);
        
        long nowTime = now.getTime();
        long weddingDayTime = weddingDay.getTime();
        System.out.println("오늘 : " + nowTime);
        System.out.println("결혼한 날 :" + weddingDayTime);
        
        long date = (nowTime - weddingDayTime) / (60*60*24*1000);
        System.out.println("경과일 :" + date);
    }
}
 
cs

< Formatter >
: 표현방식을 바꿔주는 API로 자주 사용된다.
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
package demo5;
 
import java.util.Date;
import java.text.SimpleDateFormat;
 
public class FormaterDemo1 {
 
    public static void main(String[] args) {
        
        Date today = new Date();
        System.out.println(today);
        
        String pattern1 = "yyyy";
        String pattern2 = "yyyy-MM-dd";
        String pattern3 = "yyy.MM.dd HH:mm:ss";
        
        // SimpleDateFormat
        // Date 객체가 가지고 있는 날짜/시간정보를 원하는 형식의 문자열로 변환해주는 클래스
        // 패턴문자를 사용해서 원하는 문자열 형태를 지정할 수 있다.
        //        Date -> "2019"                        패턴 : "yyyy"
        //        Date -> "19"                        패턴 : "yyyy"
        //        Date -> "2019/03/19"                패턴 : "yyyy/MM/dd"
        //        Date -> "16:37:12"                    패턴 : "HH:mm:ss"
        //        Date -> "2019년 3월 19일 화요일"    패턴 : "yyyy년 M월 d일 EEEE"
        //        Date -> "오후 4시37분"                패턴 : "a h시 m분 s초"
        // String format(Date date) : 전달받은 Date를 지정된 패턴 형식의 문자열로 변환해서 반환.
        
        SimpleDateFormat sdf = new SimpleDateFormat(pattern3);
        String text1 = sdf.format(today);
        System.out.println(text1);
    }
}
cs
SimpleDateFormat

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
package demo5;
 
import java.text.DecimalFormat;
 
public class FormatterDemo2 {
 
    public static void main(String[] args) {
        
        // DecimalFormat
        // 숫자를 원하는 형식의 문자열로 변환해주는 클래스
        // 패턴문자를 사용해서 원하는 문자열 형태로 지정할 수 있다.
        //        1000000        ->        "10,000,000"        패턴 "#,###"
        //        1000000        ->        "10,000,000"        패턴 "0,000"
        
        String pattern1 = "#,###";
        String pattern2 = "0,000";
        
        DecimalFormat df = new DecimalFormat(pattern1);
        String text = df.format(1000000);
        System.out.println(text);        
        
        String pattern3 = "#,###.##";        //> 1234.3001 >> 1,224.3        (소숫점 2번째 자리까지 표시, 끝이 0이면 표시x)
        String pattern4 = "0,000.00";        //> 1234.3001 >> 1,234.30
        
        DecimalFormat df2 = new DecimalFormat(pattern3);
        String text2 = df2.format(1234.3001);
        System.out.println(text2);
    }
}

cs

DecimalFormat

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
package demo5;
 
import java.text.MessageFormat;
 
public class FormaterDemo3 {
 
    public static void main(String[] args) {
        String[] data = {"홍길동","서울대학교","전자공학과"};
        
        String text = "이름: " + data[0+ ", 학교: " + data[1+ ", 학과: " + data[2];
        System.out.println(text);
        
        String message = "이름: {0}, 학교: {1}, 학과: {2}";
        String result = MessageFormat.format(message, data);
        System.out.println(result);
        
        String message2 = "이름{0}, 국어:{1}, 영어:{2}, 수학:{3}";
        String result2 = MessageFormat.format(message2, "홍길동"100 ,7060);
        System.out.println(result2);
    }
}
cs
MessageFormat


금일 과제 소스파일입니다.


day18_2.zip



댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/06   »
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
글 보관함