Looking to associate strings to ints in a cleaner/more efficient way

前端 未结 8 1055
孤街浪徒
孤街浪徒 2021-01-07 07:06

How can I improve this?

The relationship is one to one and continuous on [-1,5] so i was thinking of using enum, but I\'m not sure how to compare a string value to

8条回答
  •  误落风尘
    2021-01-07 07:35

    Inspired by your enum comment, I present the following. It's a bit hackish, but:

    enum Word
    {
        PROGRAM (1), BEGIN (2), END (3), INT (4), IF (5);
    
        public int value;
    
        public Word (int value)
        {
            this.value = value;
        }
    };
    
    int evaluateWord (String word)
    {
        return Word.valueOf(word.toUpperCase( )).value;
    }
    

    I love Java enums because you can do things like this. This is especially useful if you later want to (for example) add a unique behaviour for each word, or to maintain a long list of words. Note though that it is case insensitive.

    Or, alternately:

    enum Word
    {
        PROGRAM, BEGIN, END, INT, IF;
    };
    
    int evaluateWord (String word)
    {
        return Word.valueOf(word.toUpperCase( )).ordinal( ) + 1;
    }
    

提交回复
热议问题