是否有用于状态名称查找/查找的Java API或快捷方式?

时间:2013-07-09 15:14:48

标签: java api if-statement

我正在编写一个程序,它接受一个字符串,一个州名(例如New York),并输出相应的缩写(例如NY)。我的计划考虑了所有50个州,所以我的第一个想法是使用一大堆if/else if语句,但现在我认为必须有一个更好的方法...更快的方式......没有那么多看似多余的代码。

段:

if (dirtyState.equalsIgnoreCase("New York")) {
        cleanState = "NY";
    } else if (dirtyState.equalsIgnoreCase("Maryland")) {
        cleanState = "MD";
    } else if (dirtyState.equalsIgnoreCase("District of Columbia")) {
        cleanState = "DC";
    } else if (dirtyState.equalsIgnoreCase("Virginia")) {
        cleanState = "VA";
    } else if (dirtyState.equalsIgnoreCase("Alabama")) {
        cleanState = "AL";
    } else if (dirtyState.equalsIgnoreCase("California")) {
        cleanState = "CA";
    } else if (dirtyState.equalsIgnoreCase("Kentuky")) {
        cleanState = "KY";
        // and on and on...

是否有可以简化此过程的API?也许是捷径?

非常感谢任何反馈,并提前感谢=)

4 个答案:

答案 0 :(得分:2)

您可以使用TreeMap,它允许您使用不区分大小写的自定义比较器。它看起来像这样:

Map<String, String> states = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
states.put("New York", "NY");
states.put("Maryland", "MD");
//etc.

并检索缩写:

String abbreviation = states.get("new york");
System.out.println(abbreviation); //prints NY

答案 1 :(得分:1)

最好抓住city code list并将其放在属性文件中,如:

New York=NY
Maryland=MD
District of Columbia=DC
Virginia=VA

然后在Properties中加载内容并循环其条目(它扩展HashTable):

Properties cityCodes = new Properties() 
citycodes.load(new FileInputStream(...));

for(Entry<String,String> entry : cityCodes.entrySet()){
  if(dirtyState.equalsIgnoreCase(entry.getKey())){
    cleanState = entry.getValue();
  }
}

这是一个有效的例子:

public static void main(String[] args) throws Exception{
  Properties cityCodes = new Properties();
  cityCodes.load(new FileInputStream("/path/to/directory/cityCodes.properties"));
  System.out.print(getCode("Maryland",cityCodes));
}

public static String getCode(String name, Properties cityCodes){
  for(Map.Entry<Object,Object> entry : cityCodes.entrySet()){
    String cityName=(String)entry.getKey();
    String cityCode=(String)entry.getValue();

    if(name.equalsIgnoreCase(cityName)){
      return cityCode;
    }
  }
  return null;
}

输出

MD

答案 2 :(得分:1)

如果您使用的是Java 7,则可以在switch语句中使用字符串,例如:

switch (dirtyState.toLowerCase())
{ 
   case "new york": cleanState = "NY"; break;
   case "maryland": cleanState = "MD"; break;
   // so on...
}

答案 3 :(得分:0)

您可以使用枚举:

public enum State {
    AL("Alabama"), CA("California"), NY("New York");

    private State(String name) {
        this.name = name;
    }

    private String name;

    static String findByName(String name) {
        for ( int i = 0; i != values().length; ++i ) {
            if ( name.equalsIgnoreCase(values()[i].name))
                return values()[i].toString();
        }
        throw new IllegalArgumentException();
    }    
}

public class StateTest {    
    public static void main(String[] args) {
        String name = "New York";
        System.out.println(name + ": " + State.findByName(name));
    }
}