我正在尝试编写DenverSortedCities并且我确实打印了存在的文件但是我需要编写一个循环来继续阅读,而文件中有更多信息。
当循环遍历文件中的所有城市时,它将跟踪最大城市及其人口。这是我的代码:
my $t=time;
my $tel = new Net::Telnet (Timeout => 2);
eval{
$tel->open(Host=>$host,Port=>$port) || print "Not OK";
}
my $interval=time-$t;
print "Seconds: $interval";
答案 0 :(得分:0)
这是一种方法,假设您的文件是CSV
文件,其中逗号为分隔符,城市名称为第一个值,其人口为第二个值:
// Use a try-with-resource statement to close the scanner once done
try (Scanner input = new Scanner(inFile)) {
String largestCity = null;
int population = 0;
long total = 0L;
// Iterate as long as we have remaining lines in the file
while (input.hasNextLine()) {
String cityInfo = input.nextLine();
String[] cityInfoArray = cityInfo.split(",");
// Convert the second value corresponding to the population to an Integer
int populationValue = Integer.parseInt(cityInfoArray[1]);
// Check if the current population is bigger than the current largest
if (populationValue > population) {
population = populationValue;
largestCity = cityInfoArray[0];
}
total += populationValue;
}
// Print the result
System.out.printf(
"The largest city is '%s' with a population of %d inhabitants.%n",
largestCity, population
);
System.out.printf("The total population is %d.%n", total);
}