how would I use print writer and file reader properly on an arraylistwith arraylist inside?

J

justineee

Hi again,

I have an ArrayList<Word> which creates a new word with an ArrayList
of its definitions..

I am trying to use readfile and writefile to save and load the words
and definitions made by the user. It saves and loads, yes. However, it
is not properly saved and loaded. I want to save the word with
definitions as is and load it as is (so the user can still update the
words definitions or add some words). I am not very familiar with
PrintWriter and FileReader, I've been studying it for the past two
weeks and all I can do is save and load an array.

Example:

I have..

1. word
--------------------
[hello, word, thanks, again]
--------------------

-- this is the word and its definitions.

after I save.. and load it again.. this shows


1. word
------------------
[]-----------------------
----------
2.[]---
-------------------------
[]
-----------------------
3. [hello, word, thanks, again]

here is my code for load and save.

public void saveFile(ArrayList<Word> array)
throws IOException
{
PrintWriter out = new PrintWriter ("initlist.txt");
for (int ctr = 0; ctr < array.size(); ctr++)
out.println(array.get(ctr));

out.close();

}


public void loadFile(ArrayList<Word> array)
throws IOException
{
array.clear();
FileReader f = new FileReader ("initlist.txt");
Scanner input = new Scanner (f);
ArrayList<String> tempDef;
while (input.hasNextLine())
{
String word = input.nextLine();

if (array.contains(word)==false)
{
Word temp = new Word(word);
array.add(temp);
tempDef = new ArrayList<String>();

for (int aCtr = 0; aCtr < tempDef.size(); aCtr++)
{
temp.addDefinition(tempDef.get(aCtr));
}

}


}
input.close();

}


I've been trying to fix this, I just can't :|

Maybe anyone knows. Thanks.
 
C

charlesfr.rey

    tempDef = new ArrayList<String>();

     for (int aCtr = 0; aCtr < tempDef.size(); aCtr++)
     {
      temp.addDefinition(tempDef.get(aCtr));
     }

You have a bug there, you've just initialized tempDef to a new empty
ArrayList, and try to iterate over it. No temp.addDefinition(..) will
be performed.

That's a start. (And it doesn't mean that without this bug the rest is
correct).
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,055
Latest member
SlimSparkKetoACVReview

Latest Threads

Top