JCCS
JCCS

Reputation: 611

How can I add a Comma Separated ArrayList to a Tree

I have a Movie object where the data members are a String title, int year, and ArrayList actors. I am a bit confused on how I can add this ArrayList<String> to my tree. I am reading this information from a file for example:

Forrest Gump/1994/Tom Hanks
Star Wars/1977/Mark Hamill,Carrie Fisher,Harrison Ford

So far, I have been able to add everything else except for the ArrayList. I am thinking that I will need to also line.split the contents of the array. Also, some of the movies do not have multiple actors as shown in the example so I am not sure how to go about implementing this. I have tried a few different ways, but have ended up with an IndexOutOfBoundsException.

Here is what I have so far:

try{
        Scanner read = new Scanner( new File("movies.txt") );
        do{
            ArrayList<String> actorList = new ArrayList<String>();
            String line = read.nextLine();
            String [] tokens = line.split("/");
            //I think I need to add another split for commas here.
            //actorList.add() here

            tree.add( new Movie(tokens[0], Integer.parseInt(tokens[1]), actorList ));
        }while( read.hasNext() );
        read.close();
    }catch( FileNotFoundException fnf ){
        System.out.println("File not found.");
    }

Her is my Constructor if needed:

public Movie( String t, int y, ArrayList<String> a ){
    title = t;
    year = y;
    actors = a;
}

Upvotes: 0

Views: 415

Answers (3)

Nir Alfasi
Nir Alfasi

Reputation: 53525

You can split the last token by comma and insert each one of the strings that are created into the actorList:

...
String [] tokens = line.split("/");
String lastToken = tokens[tokens.length-1];
if (tokens.length == 3) {
    String[] actors = lastToken.split(",");
    for (String actor : actors) {
        actorList.add(actor);
    }
}
...

Upvotes: 1

Aakash
Aakash

Reputation: 2119

Hopefully, below code should work. Split your comma separated actor list, convert that String array to a List and add this List to your ArrayList. Use Arrays.asList() as a neat implementation.

try{
        Scanner read = new Scanner( new File("movies.txt") );
        do{
            ArrayList<String> actorList = new ArrayList<String>();
            String line = read.nextLine();
            String [] tokens = line.split("/");
            actorList.addAll(Arrays.asList(tokens[2].split(",")));

            tree.add( new Movie(tokens[0], Integer.parseInt(tokens[1]), actorList ));
        }while( read.hasNext() );
        read.close();
    }catch( FileNotFoundException fnf ){
        System.out.println("File not found.");
    }

Upvotes: 3

Tony Vu
Tony Vu

Reputation: 4361

Try this:

String actors = tokens[tokens.length-1];
actorList = Arrays.asList(actors.split(","));

Upvotes: 0

Related Questions