简体   繁体   中英

An arrayList method that reads a file and returns an ArrayList from the collected data. how do i call that array in my main method or others?

As the header asks, I need help accessing this returned array from the main and other methods. I'm checking by trying to print it out, but no errors where given, and now I am trying to print its size, but comes back at 0. any help would be appreciated.

public ArrayList<ITemperature> readDataFromFile(String fileName) throws FileNotFoundException 
{
    File file = new File("world_temp_2000-2016.csv");
    Scanner inFile = new Scanner(file);
    ArrayList<ITemperature> temp = new ArrayList<ITemperature>();

    while(inFile.hasNextLine())
    {

        String line = inFile.nextLine();
        String[] data = line.split(",");

        double tempRead = Double.parseDouble(data[0]);
        int year = Integer.parseInt(data[1]);
        String month = data[2];
        String country = data[3];
        String countryCode = data[4];

        ITemperature t = new Temperature(tempRead, year, month, country, countryCode);
        temp.add(t);

    }

    inFile.close();
    return temp;

}

public static void main(String[] args)
{
    ArrayList<ITemperature> temp = new ArrayList<ITemperature>();
    System.out.println(temp.size());
}

You haven't called method readDataFromFile(...). You have only created an empty ArrayList called temp and then tried to print its size, which is zero. Between your two lines in main(), you need to call the method you have written (surrounded by try/catch).

When you run you code only the main works.
If you want to run other functions you need to call them INSIDE your main function.

public static ArrayList<String> readDataFromFile(String fileName) throws FileNotFoundException 
{
    Scanner s = new Scanner(new File(fileName));
    ArrayList<String> list = new ArrayList<String>();
    while (s.hasNext()){
        list.add(s.next());
    }
    s.close();
    return list;
}
public static void main(String[] args) throws FileNotFoundException 
{       
    ArrayList<String> list = readDataFromFile("(enter you file path)"); //calling the function with a given path (enter the path between "")
    System.out.println(list.size()); //printing the size of the list
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM