0

テキスト ファイルから取得したデータを整理しようとしています。各行に 4 つの情報 (都市、国、人口、日付) があります。それぞれに配列が必要だったので、最初にすべてを1つの大きな文字列配列に入れ、それらを4つの配列に分割し始めましたが、人口情報を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];
                }

            }
    }

そして、配列を印刷すると、各データの間にたくさんの null があります。人口、日付などで並べ替えることができるように、4 つのデータを持つオブジェクトを作成することを計画しています。オブジェクトへのデータの原因は、まだ方法を考え出していないためです:/私の最終目標は、これらのオブジェクトの配列を取得し、それらに対してさまざまな並べ替え方法を使用できるようにすることでした

4

2 に答える 2

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 を使用していると仮定しています。私たちが話している言語は、質問またはタグとして含める必要があるものです。

于 2012-11-24T18:44:13.250 に答える
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;
    }
于 2012-11-24T18:24:56.980 に答える