如何使用Java I/O读取循环中的文件行?
我正在尝试写入DenverSortedCities,我确实打印了exist文件,但我需要编写一个循环,以便在文件中有更多信息时继续读取 当循环循环遍历文件中的所有城市时,它将跟踪最大的城市及其人口。这是我的代码:如何使用Java I/O读取循环中的文件行?,java,Java,我正在尝试写入DenverSortedCities,我确实打印了exist文件,但我需要编写一个循环,以便在文件中有更多信息时继续读取 当循环循环遍历文件中的所有城市时,它将跟踪最大的城市及其人口。这是我的代码: public static void main(String[] args) throws IOException { File inFile = new File("DenverSortedCities.txt"); if (inFile.exists()){
public static void main(String[] args) throws IOException {
File inFile = new File("DenverSortedCities.txt");
if (inFile.exists()){
Scanner input = new Scanner(inFile);
while(input.hasNextLine()){
String cityInfo = input.nextLine();
String[] cityInfoArray = cityInfo.split("0,1");
int populationValue = Integer.parseInt(cityInfo);
}
System.out.println(input.nextLine());
input.close();
} else {
System.out.println(inFile.getName() + " does not exist.");
System.exit(1);
}
}
假设您的文件是一个
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);
}
字符串cityInfo=input.nextLine()之后;字符串[]cityInfo arry=cityInfo.split(“,”);我需要执行,cityInfoarray[0]将包含城市名称,cityInfoArry[1]将包含人口。我不知道如何使用这个…只是混淆了DenverSortedCities的内容是什么?城市名称和流行音乐号码银行,这个功能只显示最大的城市和号码。。。。。但它不会显示总人口的结果,因为它会在文件中的所有城市中循环,它会跟踪最大的城市及其人口。它还会统计总人口