2012-11-24 92 views
0

我試圖組織我從文本文件中獲得的數據,每行有4條信息(城市,國家,人口和日期)。我想對每一個數組所以我第一次把它全部變成一個大的字符串數組,並開始將它們分成4列,但我需要改變的人口信息,以一個int數組,但它說,*如何將Array1 [x]的字符串賦值給Array2 [x]的int?

「類型不匹配:不能從元素int類型轉換爲字符串」

//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

問題在於你的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; 
    } 
+0

這回答了他的問題的一部分。但他確實需要爲這些數據創建一個類,而不是不同的數組 - 因爲在各個「列」之間沒有任何關聯,所以如果他稍後對總體數組進行排序,總體[0]值將不再對應於城市[0]值等 –

+0

哇謝謝,這正是我想要做的:D – Derek

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。我們正在談論哪種語言應該包含在您的問題中或作爲標籤。

+0

謝謝!我已經設立了班,但我沒有「這個」。在那裏,這會改變什麼嗎?也生病確保把語言下一次我發佈:) – Derek

+0

'這個'是沒有必要的,除非在方法中有同名的其他變量可見,正如我在上面寫的方法。 'this'只是告訴Java我們指的是對象的屬性而不是方法的參數。 –

相關問題