12일차 - Random

은채의 성장통·2025년 6월 13일

KCC정보통신

목록 보기
17/30

노션 정리

5。Locale 클래스

Locale 객체는 특정 지리적, 정치적, 문화적 영역을 나타내며, 사용자의 지역 정보를 기반으로 시스템 설정을 조정하는 역할을 합니다.

주요 생성자

  • Locale(String language): 주어진 언어 코드로 로케일 객체를 생성.
  • Locale(String language, String country): 주어진 언어 및 국가 코드로 로케일 객체를 생성.

LocaleExample 예제 코드

import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.Locale;

public class LocaleExample {
    static public void localizedFormat(String pattern, double value, Locale loc) {
        NumberFormat nf = NumberFormat.getNumberInstance(loc);
        DecimalFormat df = (DecimalFormat) nf;
        df.applyPattern(pattern);
        String output = df.format(value);
        System.out.println(pattern + "\t" + output + "\t" + loc.toString());
    }

    public static void main(String[] args) {
        Locale locale = new Locale("ko", "KR");
        System.out.println(locale.getLanguage());
        System.out.println(locale.getCountry());
        System.out.println(locale.getDisplayCountry());

        Locale locale2 = new Locale("en", "US");
        System.out.println(locale2.getLanguage());
        System.out.println(locale2.getCountry());
        System.out.println(locale2.getDisplayCountry());

        Locale[] locales = {
            new Locale("en", "US"),
            new Locale("de", "DE"),
            new Locale("fr", "FR"),
            new Locale("ko", "KR")
        };

        for (int i = 0; i < locales.length; i++) {
            localizedFormat("###,###.###", 123456.789, locales[i]);
        }
    }
}

TimeZone 클래스

TimeZone 객체는 특정 시간대의 오프셋을 나타내며, 시스템의 현재 시간대를 조정하는 역할을 합니다.

주요 메서드

  • static TimeZone getTimeZone(String ID): 주어진 시간대 ID 문자열을 기반으로 타임존 객체를 생성.
  • static TimeZone getDefault(): 시스템의 기본 타임존을 반환.

TimezoneExample 예제 코드

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;

public class TimezoneExample {
    public static void main(String[] args) {
        Calendar calendar = Calendar.getInstance();
        System.out.println((calendar.get(Calendar.ZONE_OFFSET) + calendar.get(Calendar.DST_OFFSET)) / (60 * 1000));

        TimeZone tz = TimeZone.getDefault();
        System.out.println("Timezone offset: " + tz.getID());
        System.out.println("Timezone name: " + tz.getDisplayName());
        System.out.println("Timezone ID: " + (tz.getRawOffset() / 1000 / 60) + "분");
        System.out.println("Summer Time 사용 여부: " + tz.useDaylightTime());

        Date date = new Date();
        System.out.println(date);

        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss (z Z)");
        System.out.format("%s%n%s%n%n", tz.getDisplayName(), df.format(date));

        TimeZone tz2 = TimeZone.getTimeZone("Asia/Seoul");
        df.setTimeZone(tz2);
        System.out.format("%s%n%s%n%n", tz2.getDisplayName(), df.format(date));

        TimeZone tz3 = TimeZone.getTimeZone("America/Los_Angeles");
        df.setTimeZone(tz3);
        System.out.format("%s%n%s%n%n", tz3.getDisplayName(), df.format(date));
    }
}

6。형식화 클래스

DecimalFormat 클래스

DecimalFormat 클래스는 숫자를 특정 형식에 맞춰 변환하는 기능을 제공합니다.

주요 패턴 예시

  • ###,###.### → 그룹화된 숫자 표현 (123,456.789)
  • ###.## → 소수점 이하 두 자리만 출력 (123456.79)
  • 000000.000 → 자릿수를 고정하여 출력 (012345.670)
  • #.##% → 백분율 변환 (123.45 → 12,345%)
  • #.###‰ → 퍼밀리 변환 (123.45 → 123,450‰)
  • $###,###.### → 통화 기호 포함 출력 ($12,345.67)
  • \u20A9###,###.### → 원화(₩) 표시 (₩12,345.67)

DecimalFormat 예제 코드

import java.text.DecimalFormat;

public class DecimalFormatExample {
    static public void customFormat(String pattern, double value) {
        DecimalFormat myFormatter = new DecimalFormat(pattern);
        String output = myFormatter.format(value);
        System.out.println(value + "\t" + pattern + "\t" + output);
    }

    public static void main(String[] args) {
        customFormat("###,###.###", 123456.789);
        customFormat("###.##", 123456.789);
        customFormat("000000.000", 12345.67);
        customFormat("#.##%", 123.456789);
        customFormat("#.###\u2030", 123.456789);
        customFormat("$###,###.###", 12345.67);
        customFormat("\u20a9###,###.###", 12345.67);
    }
}

SimpleDateFormat 클래스

SimpleDateFormat은 로케일에 따라 날짜 형식을 지정하고 구문 분석하는 데 사용되는 클래스입니다. 날짜를 특정 형식의 문자열로 변환하거나 문자열을 날짜로 변환하는 기능을 제공합니다.

날짜 및 시간 패턴 문자

문자설명예시
G시대 지정자AD
y연도1996, 96
Y연도(Week-based)2009, 09
MJuly, Jul, 07
w연도에서 주27
W월에서 주2
D연도에서 날짜189
d월에서 날짜10
F월에서 요일2
E주에서 요일 이름Tuesday, Tue
u주에서 요일(1 = Monday, ..., 7 = Sunday)1
a오전/오후 표시PM
H시간(0-23)22
k시간(1-24)24
K오전/오후 시간(0-11)10
h오전/오후 시간(1-12)12
m30
s55
S밀리초978
z일반 타임존PST, GMT-08:00
ZRFC 822 타임존-0800
XISO 8601 타임존-08, -0800, -08:00

날짜 및 시간 패턴 예시

예시 날짜: 2017년 3월 13일 오후 10시 16분 55초 (Asia/Seoul 타임존)

ko_KR 로케일 변환 결과

  • "yyyy.MM.dd G 'at' HH:mm:ss z"2017.03.13 서기 at 22:16:55 KST
  • "EEE, MMM d, ''yy"월, 3월 13, '17
  • "h:mm a"10:16 오후
  • "hh 'o''clock' a, zzzz"10 o'clock 오후, 한국 표준시
  • "K:mm a, z"10:16 오후, KST
  • "yyyyy.MMMMM.dd GGG hh:mm aaa"02017.3월.13 서기 10:16 오후
  • "EEE, d MMM yyyy HH:mm:ss Z"월, 13 3월 2017 22:16:55 +0900
  • "yyMMddHHmmssZ"170313221655+0900

en_US 로케일 변환 결과

  • "yyyy.MM.dd G 'at' HH:mm:ss z"2017.03.13 AD at 22:16:55 KST
  • "EEE, MMM d, ''yy"Mon, Mar 13, '17
  • "h:mm a"10:16 PM
  • "hh 'o''clock' a, zzzz"10 o'clock PM, Korea Standard Time
  • "K:mm a, z"10:16 PM, KST
  • "yyyyy.MMMMM.dd GGG hh:mm aaa"02017.March.13 AD 10:16 PM
  • "EEE, d MMM yyyy HH:mm:ss Z"Mon, 13 Mar 2017 22:16:55 +0900
  • "yyMMddHHmmssZ"170313221655+0900

DateFormatExample 예제 코드

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;

public class DateFormatExample {
    static void displayDateAndTime(String format, Locale locale, Date date) {
        DateFormat df = new SimpleDateFormat(format, locale);
        System.out.format("%s : %s%n", format, df.format(date));
    }

    public static void main(String[] args) {
        Date date = new Date();

        String[] formats = {
            "yyyy.MM.dd G 'at' HH:mm:ss z",
            "EEE, MMM d, ''yy",
            "h:mm a",
            "hh 'o''clock' a, zzzz",
            "K:mm a, z",
            "yyyyy.MMMMM.dd GGG hh:mm aaa",
            "EEE, d MMM yyyy HH:mm:ss Z",
            "yyMMddHHmmssZ"
        };

        Locale localeKR = new Locale("ko", "KR");
        Locale localeUS = new Locale("en", "US");

        System.out.println("=== Korean Locale ===");
        for (String format : formats) {
            displayDateAndTime(format, localeKR, date);
        }

        System.out.println("\n=== US Locale ===");
        for (String format : formats) {
            displayDateAndTime(format, localeUS, date);
        }
    }
}


MessageFormat 클래스(흔히 쓰지 않음 형후 국제화라는 기능을 쓴다)

MessageFormat은 다국어 환경에서 문자열을 형식화하여 출력하는 기능을 제공합니다. 특정 값을 메시지 내에서 동적으로 삽입할 때 유용합니다.

주요 패턴 형식

패턴설명
{ArgumentIndex}단순한 인수 삽입
{ArgumentIndex, FormatType}특정 형식을 적용하여 출력 (number, date, time, choice 지원)
{ArgumentIndex, FormatType, FormatStyle}상세한 형식 지정 (short, medium, long, full 등)

MessageFormat 예제 코드

import java.text.MessageFormat;
import java.util.Date;

public class MessageFormatExample {
    public static void main(String[] args) {
        Object[] arguments = {"foo", "bar", 99L};
        MessageFormat mf = new MessageFormat("1:{0} 2:{1} 3:{2}");
        System.out.println(mf.format(arguments));

        int meetingTime = 10;
        String event = "대회의실에서 면접 심사";

        String result = MessageFormat.format(
            "오늘({0, date}) {1,number,integer}시에 {2}가 있습니다.",
            new Date(), meetingTime, event);
        System.out.println(result);
    }
}

ChoiceFormat 클래스(이런것도 있구나 알아만 두자)

ChoiceFormat은 숫자 범위에 따라 문자열 출력을 조정하는 기능을 제공하며, 보통 MessageFormat과 함께 사용됩니다.

ChoiceFormat 예제 코드

import java.text.ChoiceFormat;
import java.text.ParsePosition;

public class ChoiceFormatExample1 {
    public static void main(String[] args) {
        double[] limits = {1, 2, 3, 4, 5, 6, 7};
        String[] dayOfWeekNames = {"Sun", "Mon", "Tue", "Wed", "Thur", "Fri", "Sat"};
        ChoiceFormat choiceForm = new ChoiceFormat(limits, dayOfWeekNames);

        ParsePosition status = new ParsePosition(0);
        for (double i = 0.0; i <= 8.0; i++) {
            status.setIndex(0);
            System.out.println(i + " -> " + choiceForm.format(i) + " -> "
                + choiceForm.parse(choiceForm.format(i), status));
        }
    }
}

MessageFormat과 ChoiceFormat을 함께 사용하는 예제

이 코드에서는 사과 개수에 따라 메시지를 동적으로 조정하는 방식입니다.

import java.text.ChoiceFormat;
import java.text.MessageFormat;

public class ChoiceFormatExample2 {
    public static void main(String[] args) {
        MessageFormat msgForm = new MessageFormat("{0}의 바구니에 사과가 {1}");

        double[] appleLimits = {0, 1, 2};
        String[] applePart = {"없습니다.", "1개 있습니다.", "{1,number}개 있습니다."};
        ChoiceFormat appleForm = new ChoiceFormat(appleLimits, applePart);

        msgForm.setFormatByArgumentIndex(1, appleForm);

        System.out.println(msgForm.format(new Object[]{"그", 2L}));
        System.out.println(msgForm.format(new Object[]{"그녀", 0L}));
        System.out.println(msgForm.format(new Object[]{"나", 1L}));
        System.out.println(msgForm.format(new Object[]{"너", 5L}));
    }
}

7. 수학 관련 클래스

Random 클래스

Random 클래스는 난수를 생성하는 기능을 제공합니다. Math.random()과 비교하면 더 직관적으로 다양한 형태의 난수를 만들 수 있습니다.

주요 생성자

생성자설명
Random()난수 발생 객체를 생성
Random(long seed)지정된 시드(seed)를 기반으로 난수 발생 객체를 생성

만약 동일한 시드를 사용하면 동일한 난수 시퀀스를 반복적으로 생성할 수 있습니다.

주요 메서드

반환 유형메서드설명
booleannextBoolean()true 또는 false를 임의로 반환
voidnextBytes(byte[] bytes)주어진 바이트 배열을 난수 값으로 채움
doublenextDouble()0.0 ~ 1.0 범위의 난수를 double 형으로 반환
floatnextFloat()0.0 ~ 1.0 범위의 난수를 float 형으로 반환
intnextInt()임의의 int 값 반환
intnextInt(int bound)0 ~ bound 미만의 난수 반환
longnextLong()임의의 long 값 반환
voidsetSeed(long seed)난수 생성을 위한 시드 값을 설정

Random 클래스 예제 코드

import java.util.Random;

public class RandomClassExample {
    public static void main(String[] args) {
        int numTests = 10;
        Random random = new Random();

        for (int i = 0; i < numTests; i++) {
            int randomInt = random.nextInt(100); // 0부터 99 사이의 난수 생성
            System.out.format("테스트 %2d, 발생 난수 %d\n", i + 1, randomInt);
        }
    }
}
profile
인생 별거 없어

0개의 댓글