Matching String to Enum

Discussion in 'Plugin Development' started by OMGitzFROST, Mar 5, 2022.

Thread Status:
Not open for further replies.
  1. Offline

    OMGitzFROST

    Ok so I am currently I am trying to figure out the best way to match a word to an value in my enum. For example.

    This is a test enum with items that are clearly different
    Code:
    public enum TestEnum {
        PIZZA,
        CAKE;
    }
    I am taking a message entered by the user in the chat, and lets say they wrote "I love piza". Pizza is clearly spelled wrong, but I am trying to find a way to still take the message they sent and essentially connect 'piza' to 'pizza'.

    This is what I have found online in order to potentially find the closest string.

    Code:
    public static TestEnum getMatch(String word) {
        int distance = Integer.MAX_VALUE;
        TestEnum closest = null;
        for (TestEnum compareObject : TestEnum.values()) {
            int currentDistance = StringUtils.getLevenshteinDistance(compareObject.toString(), target.toString());
            if(currentDistance < distance) {
                distance = currentDistance;
                closest = compareObject;
            }
        }
        return closest;
    }
    In-order to see If a similar word exists, I am iterating through each word inside of their message as such
    Code:
    for (String word : input.split("\\s+")) {
                TestEnum test = getMatch(word);
    
                if (test != null) {
                    // Do something once the property enum is found.
                }
            }
    The problem I am having is that sometimes it will return pizza for example and other times it will return cake etc. its never really accurate an im trying to figure out if there is a better way of doing this. Any help is appreciated thanks.
     
  2. Offline

    timtower Administrator Administrator Moderator

    You need a lower treshold as well.
     
  3. Offline

    OMGitzFROST

    Wow I dumb xD

    Well imma leave the solution here incase anyone needs it in the future

    Code:
    for (TestEnum compareObject : TestEnum.values()) {
                    int currentDistance = StringUtils.getLevenshteinDistance(input, compareObject.toString());
    
                    if (currentDistance < 3) {
                        return compareObject;
                    }
                }
     
    Last edited: Mar 5, 2022
Thread Status:
Not open for further replies.

Share This Page