存储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 楼答案
您需要将populationSize更改为array of Double并分配双值 使用正确的格式说明符表示double,我使用了
%.2f
f表示浮点数,其中包括double,2表示小数点后的两位数输出: