이 기사에서는 문자열 값으로 열거형을 조회하는 방법을 이해할 것입니다. 열거형은 상수 그룹을 나타내는 특별한 "클래스"입니다(최종 변수와 같이 변경할 수 없는 변수).
아래는 동일한 데모입니다 -
입력이 다음과 같다고 가정 -
The string is to lookup is: Java
원하는 출력은 -
The result is: JAVA
알고리즘
Step 1 - START Step 2 - Declare a string namely input_string, an object of Languages namely result. Step 3 - Define the values. Step 4 - Use the function .valueOf() to fetch the string from the enum function. Step 5 - Display the result Step 6 - Stop
예시 1
여기서는 valueOf()를 사용하여 열거형 값을 인쇄합니다.
public class Demo {
public enum Languages {
JAVA, SCALA, PYTHON, MYSQL
}
public static void main(String[] args) {
String input_string = "Java";
System.out.println("The string is to lookup is: " +input_string);
Languages result = Languages.valueOf(input_string.toUpperCase());
System.out.println("\nThe result is: ");
System.out.println(result);
}
} 출력
The string is to lookup is: Java The result is: JAVA
예시 2
여기서 .name() 함수를 사용하여 ENUM 값을 인쇄합니다.
enum Languages {
Java,
Scala,
Python,
Mysql;
}
class Demo {
public static void main(String[] args) {
System.out.println("The values of the ENUM are: ");
System.out.println(Languages.Java.name());
System.out.println(Languages.Scala.name());
System.out.println(Languages.Python.name());
System.out.println(Languages.Mysql.name());
}
} 출력
The values of the ENUM are: Java Scala Python Mysql