首页 > 解决方案 > 存储 12 个国家的名称和人口的程序,两个相同大小的数组

问题描述

使用下面的数据

国家:美国、加拿大、法国、比利时、阿根廷、卢森堡、西班牙、俄罗斯、巴西、南非、阿尔及利亚、加纳

百万人口: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]);
    
        
    
}

}

如果您从说明中注意到卢森堡假设为 0.6,但我输入了 1。每次我尝试将其设为双倍时,都会出现错误。目前我正在使用 int 但它必须是双精度的。任何建议我都很感激。我已经尝试将其更改为 double [] 但仍然出现错误。更改了人口规模,下面的循环从 int 到 double 不起作用。java中的错误

标签: javaarraysloops

解决方案


您需要将 populationSize 更改为 Double 数组并分配 double 值 使用正确的格式说明符作为 double 类型,我使用%.2ff 表示浮点数,其中包括 double 和 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 


推荐阅读