将案例切换为表等效

时间:2013-06-07 13:35:26

标签: java android

我写了这个简单的代码:

if (country.contentEquals("France"))
{
    language = "French";
}
else if (country.contentEquals("Germany"))
{
    language = "German";
}
else if (country.contentEquals("USA"))
{
    language = "English";
}

现在我想使用此表更改此代码:

static String [][] mCountryLanguageTable = {{"France","French"},  
                                            {"German","Germany"},
                                            {"USA","English"}};

是否有任何Java类型或类可以执行此操作?这只是我写的一个简单的例子

5 个答案:

答案 0 :(得分:5)

我建议使用Map或者更好的Java语言环境。这可能已经为您完成了。

Map<String, String> countryLanguageMap = new HashMap<String, String>() {{
    put("France", "French");
    put("Germany", "German");
    put("USA", "English");
}};

String country = "USA";
String language = countryLanguageMap.get(country);
if (language == null) throw new IllegalArgumentException("No mapping for country " + country);

答案 1 :(得分:1)

这个怎么样:

String language = null;
String country = ?? //Get your country here

switch(country){
    case "France":
        language = "French";
        break;

    case "US":
        language = "English";
        break;

    case "Germany":
        language = "German";
        break;

    default:
        language = "Not a valid Country selected";
}

System.out.println("Country = " + country + ", Language = " + language);

注意:Java 7以后版本支持switch条件中的字符串......

答案 2 :(得分:0)

这个怎么样?

public static String getLanguage(String country) {
    for (int i = 0; i < mCountryLanguageTable.length; i++) {
        if (mCountryLanguageTable[i][0].equals(country)) return mCountryLanguageTable[i][1];
    }
    return null;
}

答案 3 :(得分:0)

我建议使用HashMap。 http://docs.oracle.com/javase/6/docs/api/java/util/HashMap.html

HashMaps是将键与值配对的关联表。在这种情况下,您的密钥将是国家/地区,而值将是语言。

基本示例:

import java.util.*;

public static void main(String[] args) {
    HashMap countryLanguageTable = new HashMap();
    countryLanguageTable.put("France", "French");

    System.out.println(countryLanguageTable.get("France")); //prints "French"
}

答案 4 :(得分:0)

做这样的事情的最佳数据结构是Map。如果您可以将mCountryLanguageTable更改为Map,只需创建一个地图即可。另外,这是代码:

    Map<String, String> map = new HashMap<String, String>();
    for (String[] tuple : mCountryLanguageTable) {
        map.put(tuple[0], tuple[1]);
    }
    language = map.get(country);