寻找以更清洁/更有效的方式将字符串关联到int [英] Looking to associate strings to ints in a cleaner/more efficient way

查看:88
本文介绍了寻找以更清洁/更有效的方式将字符串关联到int的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何改善?

关系是一对一的,连续的[-1,5],所以我想使用枚举,但我不知道如何比较字符串值到枚举值。

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 an enum value.

如果有更好的方法,请建议。

If there is any better way to do this, please suggest.

谢谢!

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


推荐答案

你考虑过将映射填充到HashMap一次,然后只是查询地图?

Have you considered stuffing the mapping into a HashMap once, and then just querying the map?

例如,像这样:

 private static final Map<String,Integer> m_map = new HashMap<String,Integer>();
 static {
     m_map.put( "program", 1 );
     m_map.put( "begin", 2 );
     m_map.put( "end", 3 );
     m_map.put( "int", 4 );
     m_map.put( "if", 5 );
 }

 private int evaluateWord(String sval) {
     Integer value = m_map.get( sval );
     if ( null != value ) {
        return value;
     }
     else {
        System.exit(0);
     }
 }

顺便说一句,写一个解析器。用手写一个解析器是合理的。另一个选择是考虑,除非你有一个很好的理由用手写,是一个解析生成器,如 ANTLR

By the way, it looks as if you're writing a parser. It can be reasonable to write a parser by hand. Another option to consider, unless you have a good reason to write it by hand, is a parser generator like ANTLR.

这篇关于寻找以更清洁/更有效的方式将字符串关联到int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆