0

我正在编写一个程序,它接受一个字符串、一个州名(例如纽约),并输出相应的缩写(例如纽约)。我的程序考虑了所有 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

4 回答 4

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
于 2013-07-09T15:18:13.950 回答
1

最好获取一个城市代码列表并将其放在一个属性文件中,例如:

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
于 2013-07-09T15:18:35.820 回答
1

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

switch (dirtyState.toLowerCase())
{ 
   case "new york": cleanState = "NY"; break;
   case "maryland": cleanState = "MD"; break;
   // so on...
}
于 2013-07-09T15:38:47.613 回答
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));
    }
}
于 2013-07-09T16:19:27.653 回答