English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Tutoriel de base Java

Java 流程控制

Java 数组

Java 面向对象(I)

Java 面向对象(II)

Java 面向对象(III)

Gestion des exceptions Java

Java 列表(List)

Java Queue(队列)

Java Map集合

Java Set集合

Java 输入输出(I/O)

Java Reader/Writer

Java 其他主题

Java程序按字符串值查找枚举

Java example summary

在这个程序中,您将学习使用enum的valueOf()方法在Java中将字符串值转换为枚举。

示例:按字符串值查找枚举

public class EnumString {
    public enum TextStyle {
        BOLD, ITALICS, UNDERLINE, STRIKETHROUGH
    }
    public static void main(String[] args) {
        String style = "Bold";
        TextStyle textStyle = TextStyle.valueOf(style.toUpperCase());
        System.out.println(textStyle);
    }
}

When running the program, the output is:

BOLD

In the above program, we have an enum TextStyle that represents the different styles that a text block can have, that is, bold, italic, underline, and strikethrough.

We also have a string named style that contains the current style we want. But not all of them are used.

Then, we use the valueOf() method of the enum TextStyle to pass the style and get the required enum value.

Since valueOf() takes a case-sensitive string value, we must use the toUpperCase() method to convert the given string to uppercase.

On the contrary, if we use:

TextStyle.valueOf(style)

This program will throw an exception No enum constant EnumString.TextStyle.Bold.

Java example summary