【问题标题】:Program that stores the names and populations of 12 countries two arrays of the same size存储 12 个国家的名称和人口的程序,两个相同大小的数组
【发布时间】:2026-01-18 00:40:01
【问题描述】:

使用下面的数据

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

百万人口: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中的错误

【问题讨论】:

  • 错误是什么??
  • 你为什么不使用双精度数组double[] populationSize
  • 当我使用 double[] 时,我得到一个错误尝试。
  • 错误是:无法从 double 转换为 int

标签: java arrays loops


【解决方案1】:

您需要将 populationSize 更改为 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 

【讨论】:

  • 谢谢 SanjeeRM。我确实尝试了小数,现在注意到似乎 system.out .2f 是我所缺少的。这导致了我的错误
  • 如果解决了您的问题,请接受回答并点赞