我正在尝试编写一个程序,它使用ArrayLists和文件输入输出来处理一个简单的程序。 程序应读取文本文件并将每个字段存储在arraylist中,然后执行计算。该文件包含城市名称,人口和国家/地区名称。即(伦敦,7500000,英国) 当我使用命令行参数运行程序时,它应该打印语句,说明有多少城市的人口更多,等于命令行参数。
我希望有人可以指导我朝着正确的方向前进。感谢。
答案 0 :(得分:0)
没有准备好跑步'回答,我认为应该看起来像这样(伪代码)
public static void main(String[] args) {
convert first argument to integer
set up a reader for your file
while (another line is found) {
split the line by comma
convert second item in array to an integer
if integer >= integer passed in args
print current line
}
}
请记住,您必须进行异常处理(IOExceptions,NumberFormatException等)。我故意不包括保存到arraylist,因为这意味着你必须循环两次(一次在文件上,一次在列表上),这是不必要的。
答案 1 :(得分:0)
这是一个很好的学校练习: - )
假设您在C:\ temp \ cities.txt中的输入文件包含:
London,83000000,UK
Paris,22000000,France
Madrid,32000000,Spain
以下类Test.java:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
public class Test {
private static ArrayList<City> loadDataFromFile() throws IOException {
ArrayList<City> list = new ArrayList<City>();
BufferedReader br = null;
String sCurrentLine;
br = new BufferedReader(new FileReader("C:\\temp\\cities.txt"));
while ((sCurrentLine = br.readLine()) != null) {
String[] splittedLine = sCurrentLine.split(",");
City city = new City(splittedLine[0], Integer.parseInt(splittedLine[1]), splittedLine[2]);
list.add(city);
}
br.close();
return list;
}
public static void main(String[] args) throws IOException {
ArrayList<City> list = loadDataFromFile();
int input = Integer.parseInt(args[0]);
Iterator<City> it = list.iterator();
while (it.hasNext()) {
City currentCity = it.next();
if (currentCity.getPopulation() > input) {
System.out.println("Cities with population greater than " + input + " : " + currentCity.getName() + "," + currentCity.getCountry());
} else if (currentCity.getPopulation() == input) {
System.out.println("City with population equals to " + input + " : " + currentCity.getName() + "," + currentCity.getCountry());
} else {
System.out.println("Cities with population lower than " + input + " : " + currentCity.getName() + "," + currentCity.getCountry());
}
}
}
}
和一个简单的POJO:
public class City {
private String name;
private int population;
private String country;
public City(String name, int population, String country) {
this.name = name;
this.population = population;
this.country = country;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getPopulation() {
return population;
}
public void setPopulation(int population) {
this.population = population;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
}
会给你:
java Test 3200000
Cities with population greater than 32000000 : London,UK
Cities with population lower than 32000000 : Paris,France
City with population equals to 32000000 : Madrid,Spain