2016-09-14 57 views
0

我試圖通過一個數組循環,然後連接路徑加上在數組中給出的文件名。然後我想循環我已經連接起來的東西,並創建一個URL數組。但它不斷給我這個:[http://people.uncw.edu/tompkinsj/331/ch07/500.csvhttp://people.uncw.edu/tompkinsj/331/ch07/500.csvhttp://people.uncw.edu/tompkinsj/331/ch07/500.csv]這是爲什麼循環經歷多次?

而我需要它給我50.csv,100.csv和500.csv。那麼我在for循環中做了什麼錯誤?

import java.io.IOException; 
    import java.net.MalformedURLException; 
    import java.net.URL; 
    import java.util.Arrays; 
    import java.util.Scanner; 
    /** 
    * @author Unknown 
    * 
    */ 
    public class DataManager { 

     private java.lang.String[] fileNames; 
     private java.net.URL[] urls; 
     private java.util.ArrayList<java.lang.String> gameData; 
     Scanner s; 

     public DataManager(){ 
     } 
     /** 
     * Initializes the fields fileNames and path with the input parameters. 
     * Instantiates the field urls to be the same size as fileNames. 
     * Iterates over urls instantiating each url in the array invoking the constructor 
     * using path concatenated with the respective fileName from fileNames. 
     * The field gameData is then initialized using a helper method readWriteData. 
     * @param fileNames - list of csv files 
     * @param path - the base address for the csv files 
     * @throws MalformedURLException 
     */ 
     public DataManager(java.lang.String[] fileNames, java.lang.String path) throws MalformedURLException{ 
      this.fileNames = fileNames; 
      this.urls = new URL[this.fileNames.length]; 
      for (String file: this.fileNames){ 
       String concatenate = path + file; 
       URL url = new URL(concatenate); 
       for (int i = 0; i < this.urls.length; i++) { 
        this.urls[i] = url; 
        System.out.println(Arrays.toString(this.urls)); 
        } 
      } 
      } 
    public static void main(String[] args) throws IOException{ 
      String[] fileNames = { "50.csv", "100.csv", "500.csv" }; 
      String path = "http://people.uncw.edu/tompkinsj/331/ch07/"; 
      DataManager foo = new DataManager(fileNames, path);  
     } 
     } 

回答

1

由於urls循環位於文件名循環內部,因此urls將始終設置爲在for循環外部創建的最後一個url。由於urls數組和文件名數組的大小相同,因此刪除inner for循環,您將得到所需的答案。

for (int i = 0; i < this.fileNames.length; i++){ 
    String file = this.fileNames[i]; 
    String concatenate = path + file; 
    URL url = new URL(concatenate); 
    this.urls[i] = url; 
    System.out.println(Arrays.toString(this.urls)); 
} 
+0

完美!非常感謝。 – Trey

+0

看起來正確! – blackpen