2016-09-14 4 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ループはfilenamesループ内にあるため、urlは常に外側forループで作成された最後のURLに設定されます。 urls配列とfilenames配列は同じサイズなので、内部の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

関連する問題