Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Java

Nancy Melucci
PLUS
Nancy Melucci
Courses Plus Student 35,157 Points

Initializing an array from information in a text file

I have an assignment to read from a textfile (which I can do) and compare two arrays (which I also can do) but what I cannot figure out how to do is to initialize the arrays from the text, which looks like this:

"Glover 4 Blow Grumpy Crabby Hiddleston Gamble 8 Lowe Donaldson Alexander Sears Hudson Campos Cabrera Walton"

I see the array name, the size and the elements. I have tried making arraylists and just ignoring the first and second strings (Glover 4 and Gamble 8) and just adding the names that follow.

These are supposed to be a person's name, the number of friends and the names of the friends. I think I am supposed to have the scanner read in the name of the array, the size and populate each one. And then do the comparison.

I can post the code for my arraylist version if needed.

Hope that made sense. Thanks.

Nancy M.

2 Answers

Simon Coates
Simon Coates
28,694 Points

I tried demoing going from a string to your array and got the following

class Main {
  public static void main(String[] args) {
    String x = "hello world these are words";
    String[] line = x.split(" ");
    String[] result = new String[line.length-2];
    for(int i = 2; i<line.length; i++)    {
        result[i-2] = line[i];
    }
  }
}

Apart from this Array may be able to return an arraylist using what you get back from split. Anyhow, this is just an idea. I don't use java much. You can do something similar with arraylist.

Nancy Melucci
PLUS
Nancy Melucci
Courses Plus Student 35,157 Points

Thanks for taking the time to help me. I am still not sure how to make the first token in the file be the name of the array and the second be the size. I will keep working on it. I am having a lot of trouble with tokenizing and file processing.

Simon Coates
Simon Coates
28,694 Points

I'm not even sure if dynamic variable names are possible. Is using a map an option? A map on name, where the item looked up is an array using the passed in size.