Java/Study

Enum

hyunjg94 2025. 3. 4. 22:02

📌 Enum(열거형)이란?

💡 정의:

  • Enum(Enumeration)서로 관련 있는 상수(Constant) 값들의 집합을 정의할 때 사용하는 특별한 데이터 타입
  • 주로 정해진 값들만 사용해야 할 때 활용
  • : 요일, 색상, 방향, 사칙연산 기호 등
package test;

import java.util.Scanner;

public class Test {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        // 두 개의 숫자 정의
        int lv3value1 = 0;
        int lv3value2 = 0;

        System.out.println("첫 번째 정수를 입력하세요.");
        lv3value1 = scanner.nextInt();
        System.out.println("두 번째 정수를 입력하세요.");
        lv3value2 = scanner.nextInt();

        // ADD 연산 수행
        int addResult = OperatorType.ADD.lv3result(lv3value1, lv3value2);
        System.out.println(lv3value1 + " + " + lv3value2 + " = " + addResult);  // 10 + 5 = 15

        // SUB 연산 수행
        int subResult = OperatorType.SUB.lv3result(lv3value1, lv3value2);
        System.out.println(lv3value1 + " - " + lv3value2 + " = " + subResult);  // 10 - 5 = 5

        // MUL 연산 수행
        int mulResult = OperatorType.MUL.lv3result(lv3value1, lv3value2);
        System.out.println(lv3value1 + " * " + lv3value2 + " = " + mulResult);  // 10 * 5 = 50

        // DIV 연산 수행
        int divResult = OperatorType.DIV.lv3result(lv3value1, lv3value2);
        System.out.println(lv3value1 + " / " + lv3value2 + " = " + divResult);  // 10 / 5 = 2
    }
}
package test;

import java.util.function.BiFunction;

public enum OperatorType {
    ADD('+', (lv3value1, lv3value2) -> lv3value1 + lv3value2),
    SUB('-', (lv3value1, lv3value2) -> lv3value1 - lv3value2),
    MUL('*', (lv3value1, lv3value2) -> lv3value1 * lv3value2),
    DIV('/', (lv3value1, lv3value2) -> lv3value1 / lv3value2);
    
    BiFunction<Integer, Integer, Integer> function;
    private char lv3symbol;

    OperatorType(char lv3symbol, BiFunction<Integer, Integer, Integer> function){
        this.function = function;
        this.lv3symbol = lv3symbol;
    }
    
    public int lv3result(int lv3value1, int lv3value2) {
        return function.apply(lv3value1, lv3value2);
    }
}

'Java > Study' 카테고리의 다른 글

abstract  (0) 2025.03.06
Overriding ( 오버라이딩 )  (0) 2025.03.06
컬렉션 프레임워크  (0) 2025.03.03
finally  (0) 2025.03.03
static  (0) 2025.03.03