【发布时间】:2009-11-30 02:58:47
【问题描述】:
我的问题是我找不到正确显示最低人口值和拥有该值的省份的正确值的方法。:
编写一个程序来读取 省份数据文件成数组 称为 ProvinceName 和一个数组 称为省人口。你可以 假设有 10 个省。 写一个循环:将数据读入 两个数组。将数组分析为 计算总人口 所有省份。写另一个 循环查找具有 最小的人口并打印 该省的名称。
数据存储方式如下(provinceData.txt):
Ontario
12891787
Quebec
7744530
Nova Scotia
935962
New Brunswick
751527
Manitoba
1196291
British Columbia
4428356
PEI
139407
Saskatchewan
1010146
Alberta
3512368
NF/LB
508270
这是我的 Java 代码:
import java.io.*;
import java.util.Scanner;
public class Slide50
{
public static void main(String[] args)throws IOException
{
File file = new File ("C:/provinceData.txt");
Scanner in = new Scanner(file);
int i = 0;
String province[] = new String[10];
String lowProv = null;
int pop[] = new int[10];
int totalPop = 0;
int low = pop[0];
//while there is data in the file to be processed
while(in.hasNext())
{
province[i] = in.nextLine();
pop[i] = in.nextInt();
//discard the \n on the line
in.nextLine();
//regular processing goes here
i++;
}
System.out.printf("\n\t%-16s %20s\n", "Province", "Population");
System.out.printf("\t%-16s %20s\n", "========", "==========");
//print the province population report (which includes a total) using printf
for (i = 0; i < pop.length; i++)
{
System.out.printf("\t%-16s %,20d\n", province[i], pop[i]);
totalPop += pop[i];
//find the province that has the smallest population
//and print out the province name and its population
if (pop[i] < low)
{
low = pop[i];
}
}
System.out.printf("\t%-16s %20s\n", "================", "==========");
System.out.printf("\t%-16s %,20d\n", "Total:", totalPop);
System.out.println("\n\tThe province of " + lowProv + " with a population of " + low);
System.out.println("\tis the least populated of all provinces.");
}
}
这是我基于此代码运行的示例:
Province Population
======== ==========
Ontario 12,891,787
Quebec 7,744,530
Nova Scotia 935,962
New Brunswick 751,527
Manitoba 1,196,291
British Columbia 4,428,356
PEI 139,407
Saskatchewan 1,010,146
Alberta 3,512,368
NF/LB 508,270
================ ==========
Total: 33,118,644
The province of null with a population of 0
is the least populated of all provinces.
【问题讨论】: