Trey Trey - 2 months ago 9
Java Question

Why is this for loop going through multiple times?

I'm trying to loop through an Array and then concatenate the path plus the filename that is given in the array. Then I want to loop through what I've concatenated and make a URL array. But it keeps giving me this: [http://people.uncw.edu/tompkinsj/331/ch07/500.csv, http://people.uncw.edu/tompkinsj/331/ch07/500.csv, http://people.uncw.edu/tompkinsj/331/ch07/500.csv]

And I need it to give me 50.csv, 100.csv, and 500.csv. So what am I doing wrong in the for loop?

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);
}
}

Answer

Since the urls loop is inside the filenames loop, the urls will always be set to the last url created in the outer for loop. Since the urls array and the filenames array are the same size, remove the inner for loop, and you will get the desired answer.

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));
}
Comments