【发布时间】:2016-11-13 03:33:13
【问题描述】:
我正在处理的一些文件:http://pastebin.com/WriQcuPs
目前我必须制作人口、纬度和经度字符串,否则我将无法获得所需的输出。我希望它们按顺序是 int、double 和 double。
public class City {
String countrycode;
String city;
String region;
String population;
String latitude;
String longitude;
public City (String countrycode, String city, String region, String population, String latitude, String longitude) {
this.countrycode = countrycode;
this.city = city;
this.region = region;
this.population = population;
this.latitude = latitude;
this.longitude = longitude;
}
public String toString() {
return this.city + "," + this.population
+ "," + this.latitude + ","
+ this.longitude;
}
}
我怀疑这与我创建数组列表的方式有关。有没有办法使列表中的某些元素具有不同的类型?我尝试将其更改为 ArrayList<City> 并更改 City 类中的数据类型,但它仍然给了我很多错误。
public class Reader {
In input = new In("file:world_cities.txt");
private static City cityInfo;
public static void main(String[] args) {
// open file
In input = new In("world_cities.txt");
input = new In("world_cities.txt");
try {
// write output to file
FileWriter fw = new FileWriter("cities_out.txt");
PrintWriter pw = new PrintWriter(fw);
int line = 0;
// iterate through all lines in the file
while (line < 47913) {
// read line
String cityLine = input.readLine();
// create array list
ArrayList<String> cityList = new ArrayList<String>(Arrays.asList(cityLine.split(",")));
// add line to array list
cityList.add(cityLine);
// increase counter
line += 1;
// create instance
cityInfo = new City(cityList.get(0), cityList.get(1), cityList.get(2), cityList.get(3), cityList.get(4), cityList.get(5));
System.out.println(cityInfo);
// print output to file
pw.println(cityInfo);
}
// close file
pw.close();
}
// what is printed when there is an error when saving to file
catch (Exception e) {
System.out.println("ERROR!");
}
// close the file
input.close();
}
}
【问题讨论】: