使用国家/地区对象填充数组

时间:2014-01-26 04:21:05

标签: java arrays object

我正在编写java风险游戏。我有一个名为countries的类,它将有一个填充了country类型对象的数组。如何使用42个国家/地区对象填充数组。我想也许可以使用for循环填充阵列,但我不知道如何让它填满所有不同的国家。

1 个答案:

答案 0 :(得分:0)

简化的方法是使用ISO country codesthis link提供了一种有效的处理方法。

我已经调整了代码来处理异常并将比较器分开(下面的工作代码):

public static void main(String[] args) {
        List<Country> countries = new ArrayList<Country>();

        Locale[] locales = Locale.getAvailableLocales();
        for (Locale locale : locales) {
            try {
                String iso = locale.getISO3Country();
                String code = locale.getCountry();
                String name = locale.getDisplayCountry();

                if (!"".equals(iso) && !"".equals(code) && !"".equals(name)) {
                    countries.add(new Country(iso, code, name));
                }
            } catch (MissingResourceException ex) {

            }
        }

        for (Country country : countries) {
            System.out.println(country);
        }
    }
}

class Country {
    private String iso;

    private String code;

    public String name;

    Country(String iso, String code, String name) {
        this.iso = iso;
        this.code = code;
        this.name = name;
    }

    public String toString() {
        return iso + " - " + code + " - " + name.toUpperCase();
    }

<强>输出:

MYS - MY - MALAYSIA
QAT - QA - QATAR
ISL - IS - ICELAND
FIN - FI - FINLAND
MLT - MT - MALTA
CHE - CH - SWITZERLAND
BEL - BE - BELGIUM
...
相关问题