Comparing words from a text to an Enum’s list

Asked

Viewed 466 times

4

I have an Enum that contains a list of values. I have a method where I receive text as a parameter. This method, besides going through Enum, breaks the text by words. The main function of the method is to see if there is any word in the text that is equal to any value in the Enum. The code is below:

public String checkTipo(String texto) {
        List<TipoPokemon> lista = Arrays.asList(TipoPokemon.values());
        String palavras[] = texto.split(" ");

        for(int i=0 ; i < lista.size() ; i++){
        for (String palavra : palavras){
            String tipo = lista.get(i).getNome();
                if (palavra.toLowerCase().equals(tipo)){
                    return "Olá";
                }
            }
        }

        return "";
    }

My Enum is:

package br.com.pokemax.modelo;

public enum TipoPokemon {

    FIRE("FIRE"),
    WATER("WATER"),
    GRASS("GRASS"),
    ELECTRIC("ELECTRIC"),
    ICE("ICE"),
    DARK("DARK"),
    GHOST("GHOST"),
    FAIRY("FAIRY"),
    PSYCHIC("PSYCHIC"),
    DRAGON("DRAGON"),
    POISON("POISON"),
    GROUND("GROUND"),
    ROCK("ROCK"),
    NORMAL("NORMAL"),
    BUG("BUG"),
    FIGHTING("FIGHTING"),
    STEEL("STEEL"),
    FLYING("FLYING");

    private String nome;

    private TipoPokemon(String nome) {
        this.nome = nome;
    }

    public String getNome() {
        return nome;
    }

    public void setNome(String nome) {
        this.nome = nome;
    }

}

I’m trying to debug and the part where I create the variable guy, he returns in foreach and does not check the if, I need to compare word with enum, someone can help me ?

  • I don’t understand what your question is. Is the code not working? If not, what goes wrong? What are the types of Pokémon you have on your Enum? If the code does not work, could give an example of text in which it does not work, but should work?

  • I’ll edit the question.

  • You could join the contents of your list of values into a string, like: "value1;value2;Valor3;value4;value5" and then ask in a loop if a stringvalues.contains(word)

  • Edited question @Victorstafusa.

2 answers

5


You don’t need to define the name that way because everyIn has a method name() that does exactly what your getNome() ago.

In addition, every Enum has a method valueOf(String) that makes a part of what your checkTipo(String) ago.

Your code would look like this:

package br.com.pokemax.modelo;

import java.util.Locale;

public enum TipoPokemon {
    FIRE, WATER, GRASS, ELECTRIC, ICE, DARK, GHOST, FAIRY, PSYCHIC,
    DRAGON, POISON, GROUND, ROCK, NORMAL, BUG, FIGHTING, STEEL, FLYING;

    public static String checkTipo(String texto) {
        String palavras[] = texto.split(" ");
        for (String palavra : palavras) {
            try {
                TipoPokemon tipo = valueOf(palavra.toUpperCase(Locale.ROOT));
                return "Olá";
            } catch (IllegalArgumentException e) {
                // Ignora a exceção e continua no for.
            }
        }
        return "";
    }
}

I just don’t understand why the method returns "Olá" or "" instead of returning boolean or the TipoPokemon found.

Here’s a test for him:

public static void main(String[] args) {
    System.out.println(TipoPokemon.checkTipo("ROCK"));
    System.out.println(TipoPokemon.checkTipo("bug"));
    System.out.println(TipoPokemon.checkTipo("banana"));
    System.out.println(TipoPokemon.checkTipo("banana cereja acerola"));
    System.out.println(TipoPokemon.checkTipo("banana cereja dark acerola"));
}

Here’s the way out:

Olá
Olá


Olá

See here working on ideone.

  • Thanks, I got another way too... I’ll post another question I’ll ask.

  • What Locale.ROOT does ?

  • @Douglas Make sure your code doesn’t stick if you are running in Turkey - http://stackoverflow.com/questions/11063102/using-locales-with-javas-tolowercase-and-touppercase - This is because the upper and lower case rules are different in Turkey. Therefore, use the toLowerCase() and the toUpperCase() without parameters is something considered as bad programming practice by some people. Some tools that analyze code automatically, such as Findbugs, also point to this as a possible cause of problems. The solution is to put the Locale.ROOT.

  • I get it... thank you

2

One option without needing to capture exception:

public boolean checkTipo(String texto) {
    List<String> palavras = Arrays.asList(texto.toUpperCase().split(" "));

    for (TipoPokemon tipoPokemon : TipoPokemon.values()) {
        if (palavras.indexOf(tipoPokemon.name()) > -1) {
            return true;
        }
    }
    return false;
}

As clarified in @Victor Stafusa’s reply you do not need to assign a string to each Enum item if the string is equal to the item’s name; the function name() I already extracted this string for you.

Testing:

@Test
public void checkTipo() {
    assertTrue(checkTipo("não dark outro"));
    assertFalse(checkTipo("não darkness outro"));
}
  • Thank you, but I do not know if you will meet me.... I asked another question now further detailing my ultimate goal.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.