有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

使用下面的数据

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

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


共 (1) 个答案

  1. # 1 楼答案

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