我正在尝试组织我从文本文件中提供的数据,每行有4条信息(城市,国家,人口和日期)。我希望每个都有一个数组,所以我先将它们全部放入一个大的String数组中,然后开始将它们分成4个数组,但我需要将Population信息更改为int数组,但是它表示*
“类型不匹配:无法从元素类型int转换为String”
//Separate the information by commas
while(sc.hasNextLine()){
String line = sc.nextLine();
input = line.split(",");
//Organize the data into 4 seperate arrays
for(int x=0; x<input.length;x++){
if(x%4==0){
cities[x] = input[x];
}
if(x%4==1){
countries[x] = input[x];
}
if(x%4==2){
population[x] = Integer.parseInt(input[x]);
}
if(x%4==3){
dates[x] = input[x];
}
}
}
当我打印出数组时,每个数据之间都有一堆空值。我打算创建具有4个数据的对象,这样我就可以按人口,日期等对它们进行排序......我很擅长处理对象,所以如果有人有更好的方法来获取4个数据因为我还没有找到一个方法:/我的最终目标是拥有这些对象的数组,我可以对它们进行不同的排序方法
答案 0 :(得分:1)
我建议做这样的事情:
public class MyData {
private String city;
private String country;
private Integer population;
private String date;
public MyData(String city, String, country, Integer population, String date) {
this.city = city;
this.country = country;
this.population = population;
this.date = date;
}
// Add getters and setters here
}
然后在你发布的文件中:
...
ArrayList<MyData> allData = new ArrayList<MyData>();
while(sc.hasNextLine()) {
String[] values = sc.nextLine().split(",");
allData.add(new MyData(values[0], values[1], Integer.parseInt(values[2]), values[3]));
}
...
您需要一个对象来存储数据,以便保持每列中值之间的关系。
另外,我只是假设你在这里使用Java。我们所谈论的语言应该包含在您的问题中或作为标记。
答案 1 :(得分:0)
问题在于您的x索引。如果仔细查看“for”,您会看到它会在每3个位置插入一个值。
试
int index = 0;
while(sc.hasNextLine()){
String line = sc.nextLine();
input = line.split(",");
//Organize the data into 4 seperate arrays
for(int x=0; x<input.length;x++){
if(x%4==0){
cities[index] = input[x];
}
if(x%4==1){
countries[index] = input[x];
}
if(x%4==2){
population[index] = Integer.parseInt(input[x]);
}
if(x%4==3){
dates[index] = input[x];
}
}
++index;
}