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

前端 未结 8 1042
孤街浪徒
孤街浪徒 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条回答
  •  梦毁少年i
    2021-01-07 07:55

    Why do you need a (very subjective) "cleaner" way?

    You could get more efficiency from using a hash lookup but you'd want to be certain it's called quite a bit to make the extra coding effort worthwhile. If it's something that happens infrequently (and, by that, I mean something like less than once a second), it's not worth doing (YAGNI).

    One thing you might want to do for better looking code (if that's important) is to ditch the else bits, they're totally unnecessary:

    private int evaluateWord(String sval) {
        if (sval.equals("program")) return 1;
        if (sval.equals("begin"))   return 2;
        if (sval.equals("end"))     return 3;
        if (sval.equals("int"))     return 4;
        if (sval.equals("if"))      return 5;
        System.exit(0);
    }
    

提交回复
热议问题