简体   繁体   中英

Creating objects from String array based off a line from a BufferedReader?

i have been scratching around this problem and it has me stumped.

I have a class with that holds an array list of objects from another class. I am trying to use a buffered reader to get data for objects from a text file. The text file holds the information for a new object on each line. I am having trouble looping the data into objects. Each time I try all of the objects have the data from the last line of the text document.

This is the block of code from the class where the array list lives.

package weatherapp;
import java.util.*;
import java.io.*;
import java.util.logging.Level;
import java.util.logging.Logger;

public class WeatherHistory extends WeatherObservation{
    BufferedWriter writer = null;
    BufferedReader reader = null;
    File myFile = new File("observations.txt");
    FileReader fileReader  = null;
    WeatherObservation readIn = new WeatherObservation();
    float tempReadIn;
    int humidReadIn;
    int UVReadIn;
    int windSpeedReadIn;
    int lineCounter = 0;

    WeatherHistory(){    
}

private ArrayList<WeatherObservation> list = new ArrayList<>();
int index;


//Add elements to the list
public void add(WeatherObservation item){
    list.add(item);
}

public void indexAdd(int index, WeatherObservation item){
    list.add(index, item);
}

//remove elements from the list
public void remove(WeatherObservation item){
    list.remove(item);
}

public  void indexRemove(int index){
    list.remove(index);
}

//update element
public void set(int index, WeatherObservation item){
    list.set(index, item);
}

//Return index of an object
public int indexOf(WeatherObservation item){
    return list.indexOf(item);
}

//return object at an idex
public WeatherObservation get(int index){
    return list.get(index);    
}

//Get size of array list
public int size(){
    return list.size();
}

//search list
public boolean search(WeatherObservation item){
    return list.contains(item);
}


//Print list
public void getList(){
    for(int counter = 0; counter < list.size(); counter++){
        System.out.println(list.get(counter));
    } 
}    


    public void add(){        

        try{ 
        fileReader = new FileReader(myFile);
        reader = new BufferedReader(fileReader);
        reader.readLine();
        //Skip over the first line to get to the data
        String line = null;

        while((line = reader.readLine()) !=null){
        lineCounter ++;            
        String[ ] data = line.split(" ");

        //get place and date from array
        readIn.place(data[0]);
        readIn.dateDay(data[1]);
        System.out.println(line);         

        //convert String from array to needed format       
         try
    {
        tempReadIn = Float.valueOf(data[2]);
        humidReadIn = Integer.parseInt(data[3]);
        UVReadIn = Integer.parseInt(data[4]);
        windSpeedReadIn = Integer.parseInt(data[5]);
    }
    catch (NumberFormatException nfe)
    {
      Logger.getLogger(WeatherHistory.class.getName()).log(Level.SEVERE,
                    null, nfe);
    }         
        readIn.temp(tempReadIn);
        readIn.humid(humidReadIn);
        readIn.uvIndex(UVReadIn);
        readIn.windSpeed(windSpeedReadIn);





        }    
        }   catch (IOException ex){
            Logger.getLogger(WeatherHistory.class.getName()).log(Level.SEVERE,
                    null, ex);        

        } finally {
            try{
            if(reader !=null){
            reader.close();
        }
        } catch (IOException ex){
            Logger.getLogger(WeatherHistory.class.getName()).log(Level.SEVERE,
                    null, ex);
    }



        }

        for(int j = 0;j < lineCounter; j++){ 
                list.add(readIn);

        }
    }
}

When I print the list out all objects have the same data and its the data from the last object added.

package weatherapp;


public class WeatherApp {


    public static void main(String[] args) {

        WeatherHistory WHtest = new WeatherHistory(); 




WHtest.add();

WHtest.getList();



    }
}

How do add the objects to the array list properly?

Turns out i added one object to all spots of the list.

all objects have the same data

What 'all objects'? You're adding the same object to every position in the array. There is only one object, so of course it always has the same data.

I worked it out. Thanks to EJB letting me know i was reusing the same object.

I moved

WeatherObservation readIn = new WeatherObservation();

to inside the while loop

I got rid of the for loop -

    for(int j = 0;j < lineCounter; j++){ 
            list.add(readIn);

    }

and placed

list.add(readIn)

from the for loop inside the while loop

I hope this helps anyone who was having similar problems.

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