views:

71

answers:

1

Hi, I'm having trouble parsing input from a file. The file is separated by lines, using ':' as a delimeter value. I'm having trouble getting the input into an ArrayList, and I think it's because I'm ineffectively using a variable within the while loop. If the variable newItin changes, it is still referencing the same object, or rather is the 'itinerary' ArrayList appending newItin, or rather just changing it. I was wondering if anyone had any suggestions as to how I could fix this. Thank you in advance.

    ArrayList <Itinerary> itinerary = new ArrayList <Itinerary>();
    Itinerary newItin = new Itinerary();
    fileIn.useDelimiter(":");

    while(fileIn.hasNextLine()){
        if(fileIn.hasNext()){
        String dest = fileIn.next();
        String days = fileIn.next();
        newItin.addDestination(dest, Integer.parseInt(days));
        itinerary.add(newItin);}
        fileIn.nextLine();}
    fileIn.close();
+1  A: 

You need to move the 'new Itinerary' into the loop and make a new one every time. Otherwise you keep adding the same object to the ArrayList over and over.

bmargulies