java—存储12个国家的名称和人口的程序—两个大小相同的数组

l7mqbcuq  于 2021-08-25  发布在  Java
关注(0)|答案(1)|浏览(333)

使用下面的数据
国家:美国、加拿大、法国、比利时、阿根廷、 lucene 堡、西班牙、俄罗斯、巴西、南非、阿尔及利亚、加纳
百万人口:327、37、67、11、44、0.6、46、144、209、56、41、28

使用两个可以并行使用的数组来存储国家及其人口的名称。

写一个循环,整齐地打印每个国家的名称和人口。

public static void main(String[] args) 
{

    // 12 countries and population size

    String[] countryName = {"USA", "Canada", "France", "Belgium", "Argentina", "Luxembourg", 
                            "Spain", "Russia", "Brazil", "South Africa", "Algeria", "Ghana"}; //declare the country

    int[] populationSize = {327, 37, 67, 11, 44, 1, 
                            46, 144, 209, 56, 41, 28}; // declare the population

    // A parallel array are when the position match each other ex usa postion 0 and 327 position 0

    for
    (
            int i = 0; i <=11; i++
    )
            System.out.printf("Country: %s, Population in millions: %d \n", countryName[i], populationSize [i]);

}

}
如果你从说明中注意到 lucene 堡值应该是0.6,但我把它设为1。每次我尝试将它设为双精度,我都会得到一个错误。目前我使用int,但它必须是一个双精度。任何建议我都很感激。我已经尝试将其更改为double[],但仍然出现错误。将总体大小和下面的循环从int更改为double无效。java中的错误

f87krz0w

f87krz0w1#

您需要将populationsize更改为array of double,并为double指定双值。我使用了正确的格式说明符 %.2f f表示浮点数,其中包括双精度,2表示小数点后的两位数字

public static void main(String[] args)  {

        // 12 countries and population size

        String[] countryName = {"USA", "Canada", "France", "Belgium", "Argentina", "Luxembourg", 
                "Spain", "Russia", "Brazil", "South Africa", "Algeria", "Ghana"}; //declare the country

        Double[] populationSize = {327.0, 37.0, 67.0, 11.0, 44.0, 0.6, 
                46.0, 144.0, 209.0, 56.0, 41.0, 28.0}; // declare the population

        // A parallel array are when the position match each other ex usa postion 0 and 327 position 0

        for (int i = 0; i <=11; i++ ) {
            System.out.printf("Country: %s, Population in millions: %.2f \n", countryName[i], populationSize [i]);
        }
    }

输出:

Country: USA, Population in millions: 327.00 
Country: Canada, Population in millions: 37.00 
Country: France, Population in millions: 67.00 
Country: Belgium, Population in millions: 11.00 
Country: Argentina, Population in millions: 44.00 
Country: Luxembourg, Population in millions: 0.60 
Country: Spain, Population in millions: 46.00 
Country: Russia, Population in millions: 144.00 
Country: Brazil, Population in millions: 209.00 
Country: South Africa, Population in millions: 56.00 
Country: Algeria, Population in millions: 41.00 
Country: Ghana, Population in millions: 28.00

相关问题