0

This code works, but with a try/catch box .

public enum AccentuationUTF8 {/** */
        é, /** */è, /** */ç, /** */à, /** */ù, /** */
        ä, /** */ë, /** */ö, /** */ï, /** */ü, /** */
        â, /** */ê, /** */î, /** */ô, /** */û, /** */
}
......

    final EnumSet<AccentuationUTF8> esUtf8 = EnumSet.noneOf(AccentuationUTF8.class);
    final String[] acc1 = {"é", "à", "u"};
    for (final String string : acc1) {
        try { // The ontologic problem
            esUtf8.add(AccentuationUTF8.valueOf(string));
        } catch (final Exception e) {
            System.out.println(string + " not an accent.");
        }
    }
    System.out.println(esUtf8.size() + "\t" + esUtf8.toString()

output :

u   not an accent.
2   [é, à]

I want to generate an EnumSet with all accents of a word or of sentence.

Edit after comments

  • Is it possible to manage such an EnumSet without using try (needed by AccentuationUTF8.valueOf(string)?
  • Is better way to code ?

FINAL EDIT

Your responses suggest me a good solution : because EnumSet.contains(Object), throw an Exception, change it : create a temporary HashSet able to return a null without Exception.

So the ugly try/catch is now removed, code is now :

final Set<String> setTmp = new HashSet<>(AccentsUTF8.values().length);
for (final AccentsUTF8 object : AccentsUTF8.values()) {
    setTmp.add(object.toString());
}
final EnumSet<AccentsUTF8> esUtf8 = EnumSet.noneOf(AccentsUTF8.class);
final String[] acc1 = {"é", "à", "u"};
for (final String string : acc1) {
    if (setTmp.contains(string)) {
        esUtf8.add(AccentsUTF8.valueOf(string));
    } else {
        System.out.println(string + " not an accent.");
    }
}
System.out.println(esUtf8.size() + "\t" + esUtf8.toString() 

Thanks for attention you paid for.

4

1 回答 1

2

我不认为枚举是这里最好的方法——部分原因是它只适用于有效的 Java 标识符。

看起来您真正想要的只是一个Set<Character>,类似于:

Set<Character> accentsInText = new HashSet<Character>();
for (int i = 0; i < text.length(); i++) {
    Character c = text.charAt(i);
    if (ALL_ACCENTS.contains(c)) {
        accentsInText.add(c);
    }
}
于 2012-08-07T10:08:00.773 回答