为什么这个for循环经历了多次?

时间:2016-09-14 19:17:49

标签: java

我正在尝试遍历一个数组,然后连接路径加上数组中给出的文件名。然后我想循环我连接的内容并创建一个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 个答案:

答案 0 :(得分:1)

由于urls循环位于文件名循环中,因此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));
}