开发者

Parsing input from file into an ADT ArrayList

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);}
        f开发者_开发知识库ileIn.nextLine();}
    fileIn.close();


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜